linux - [Solved-5 Solutions] How to make child process die after parent exits - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
How to make child process die after parent exits ?
Linux - Solution 1:
Child can ask kernel to deliver SIGHUP (or other signal) when parent dies by specifying option PR_SET_PDEATHSIG in prctl() syscall like this:
Linux - Solution 2:
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
Linux - Solution 3:
If you're unable to modify the child process, you can try something like the following:
- This runs the child from within a shell process with job control enabled. The child process is spawned in the background.
- The shell waits for a newline (or an EOF) then kills the child.
- When the parent dies--no matter what the reason--it will close its end of the pipe.
- The child shell will get an EOF from the read and proceed to kill the backgrounded child process.
Linux - Solution 4:
On Mac OS X you can use kqueue:
Linux - Solution 5:
This type of solution is useful when the code in the child can't be modified.
There are two small caveats with this method:
- If you deliberately kill the intermediate process, then the child won't be killed when the parent dies.
- If the child exits before the parent, then the intermediate process will try to kill the original child pid, which could now refer to a different process. (This could be fixed with more code in the intermediate process.)