How can I detect parent process death in Linux OS?
If in parent process called fork()
, that create child process. In the parent process I can use system call wait()
for waiting terminated child process, and getting its status.
But, I can't find info about how child process can detect parent process' death?
You can get the parent process id by calling getppid()
and then sending signal 0 via kill()
. A return code of 0 will indicate that the process is still alive.
As mentioned by @Ariel, getppid()
will either return the pid of the original parent or that of init, which will be pid 1. So you either have to store the parent pid by calling getppid()
at startup or later check if your parent has pid 1.
According to this answer on Linux you can also detect the death of the parent via prctl()
's PR_SET_PDEATHSIG
option and a self-chosen signal.
In my Ubuntu 16.04.1 LTS getppid() returns no "1" but id of process "/sbin/upstart --user" after parent kill, so checking getppid() == 1 will not work and getppid() should be saved at child start and later compared.
If both the parent and child process are under your control for their lifetime, the most portable method is to share one half of a pipe or socket with the parent.
- Prior to fork, open a pipe() or socketpair().
- After fork,
- in the parent, close the read end of the pipe, or the first socket.
- in the child, close the write end of the pipe, or the second socket.
- In the parent, stash the remaining file descriptor away and forget about it.
- In the child, use any of the multiplexed IO methods (select, poll, etc.) to test the descriptor for readability
- If the descriptor becomes readable, the parent is almost certainly dead, or some rare bug caused a stray write, which you can check for by calling read(). If the parent really was dead, read() will return 0 bytes.
The advantage of this method is that it completely avoids signals, which are one of the hardest to master mechanisms in UNIX, and provides a waitable descriptor that can easily be integrated with a network multiplexer or GUI event loop.