Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 499
dave mankoff Avatar asked Apr 18 '11 16:04

dave mankoff


People also ask

What happens to child process if parent is killed?

Orphan Processes When a parent process dies before a child process, the kernel knows that it's not going to get a wait call, so instead it makes these processes "orphans" and puts them under the care of init (remember mother of all processes).

Does exit kill child processes?

If the process calling _exit() is a controlling process, _exit() disassociates the associated controlling terminal from the session. A new controlling process can then acquire the terminal. Exiting from a process does not end its child processes directly.

How can a process determine if it is the parent process or the child process?

A child process is created as its parent process's copy and inherits most of its attributes. If a child process has no parent process, it was created directly by the kernel. If a child process exits or is interrupted, then a SIGCHLD signal is send to the parent process.

What is the process that is running but has its parent process terminated called?

Explanation: Cascading termination refers to termination of all child processes if the parent process terminates Normally or Abnormally. Some systems don't allow child processes to exist if the parent process has terminated. Cascading termination is normally initiated by the operating system. 4.


2 Answers

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.

like image 113
Michał Šrajer Avatar answered Sep 28 '22 08:09

Michał Šrajer


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.

like image 38
Andrew E. Falcon Avatar answered Sep 28 '22 07:09

Andrew E. Falcon