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?
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).
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With