Unexpected Loss Of Parent Process

Usually it is the parent process that monitors children with wait(2), though sometimes you may want a child process to detect when the parent has gone away. Perhaps the child is holding a lock, and needs to close that lock should the parent unexpectedly exit. Power users can be fast and loose with KILL signals, or the parent process could crash.

A Bad Script

One solution would be to check the parent PID, though this has various problems. The parent PID might already be 1 if the process is run by init(8) so there would be nothing to reparent to, or on the portability front some operating systems will reparent to some other PID that is not 1, or anyways there is a race condition: the parent might already have crashed or have been killed by the time the child can call getppid(2). Hence the spoiler in the title for this section.

bad.pl

Yet Another Use For A Pipe

Another method (used elsewhere for other tricks on this capsule) is to setup a pipe, and then the child can react when that pipe goes away. This does consume a file descriptor, but hopefully you are not running short on those.

pipewatch.pl

Downsides may involve systems that do not support pipes, in which case you may need to use a socket or a temporary file, or to instead stop using Windows. Or maybe instead design things so that a child process need not be aware of whether the parent or worse some ancestor is still around, but that may not always be possible.

Also, avoid using the KILL signal if at all possible. Unless that process is Firefox, though it is more rare these days that large and bad software needs to be gotten rid of that way.

tags #unix