Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure or anything else) I want the child process to die. How to do that correctly?
Some similar question on stackoverflow:
- (asked earlier) How can I cause a child process to exit when the parent does?
- (asked later) Are child processes created with fork() automatically killed when the parent is killed?
Some similar question on stackoverflow for Windows:
I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions. This is mental masturbation, but works.
The trick is:
That way:
Shortcomings:
Does the child process have a pipe to/from the parent process? If so, you'd receive a SIGPIPE if writing, or get EOF when reading - these conditions could be detected.
If you send a signal to the pid 0, using for instance
that signal is sent to the entire process group, thus effectively killing the child.
You can test it easily with something like:
If you then press ^D, you'll see the text
"Terminated"
as an indication that the Python interpreter have indeed been killed, instead of just exited because of stdin being closed.I have achieved this in the past by running the "original" code in the "child" and the "spawned" code in the "parent" (that is: you reverse the usual sense of the test after
fork()
). Then trap SIGCHLD in the "spawned" code...May not be possible in your case, but cute when it works.
As other people have pointed out, relying on the parent pid to become 1 when the parent exits is non-portable. Instead of waiting for a specific parent process ID, just wait for the ID to change:
Add a micro-sleep as desired if you don't want to poll at full speed.
This option seems simpler to me than using a pipe or relying on signals.
I think a quick and dirty way is to create a pipe between child and parent. When parent exits, children will receive a SIGPIPE.