views:

556

answers:

3

Is there a way for a child process in Python to detect if the parent process has died?

+1  A: 

You might get away with reading your parent process' ID very early in your process, and then checking, but of course that is prone to race conditions. The parent that did the spawn might have died immediately, and even before your process got to execute its first instruction.

Unless you have a way of verifying if a given PID refers to the "expected" parent, I think it's hard to do reliably.

unwind
+2  A: 

If your Python process is running under Linux, and the prctl() system call is exposed, you can use the answer here.

This can cause a signal to be sent to the child when the parent process dies.

Alnitak
A: 

The only reliable way I know of is to create a pipe specifically for this purpose. The child will have to repeatedly attempt to read from the pipe, preferably in a non-blocking fashion, or using select. It will get an error when the pipe does not exist anymore (presumably because of the parent's death).

Ringding