How to Detect in Sub Process When Parent Process Has Died?

1.8k Views Asked by At

In python, I have a parent process that spawns a handful of child processes. I've run into a situation where, due to an unhandled exception, the parent process was dieing and the child processes where left orphaned. How do I get the child processes to recognize that they've lost their parent?

I tried some code that hooks the child process up to every available signal and none of them were fired. I could theoretically put a giant try/except around the parent process to ensure that it at least fires a sigterm to the children, but this is inelegant and not foolproof. How can I prevent orphaned processes?

2

There are 2 best solutions below

2
On BEST ANSWER

You can use socketpair() to create a pair of unix domain sockets before creating the subprocess. Have the parent have one end open, and the child the other end open. When the parent exits, it's end of the socket will shut down. Then the child will know it exited because it can select()/poll() for read events from its socket and receive end of file at that time.

0
On

on UNIX (including Linux):

def is_parent_running():
    try:
        os.kill(os.getppid(), 0)
        return True
    except OSError:
        return False

Note, that on UNIX, signal 0 is not a real signal. It is used just to test if given process exists. See manual for kill command.