Child process detecting death of parent process in Python

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

+7
python subprocess
source share
4 answers

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

This can lead to a signal being sent to the child when the parent process dies.

+3
source share

You can slip away from reading your parent process identifier very early in your process and then check, but of course, this is prone to race conditions. The parent who spawned may have died right away, and even before your process completed its first instruction.

If you have a way to check if a given PID belongs to an โ€œexpectedโ€ parent, I think this is hard to do reliably.

+1
source share

The only reliable way that I know is to create a channel specifically for this purpose. The child will have to repeatedly try to read from the pipe, preferably in a non-blocking way, or by using a choice. He will get an error when the pipe no longer exists (presumably due to parental death).

+1
source share

Assuming the parent is alive when you start doing this, you can check if he is alive in the busy cycle as such using psutil :

 import psutil, os, time me = psutil.Process(os.getpid()) while 1: if me.parent is not None: # still alive time.sleep(0.1) continue else: print "my parent is gone" 

Not very nice, but ...

+1
source share

All Articles