How to detect in a subprocess when a parent process has died?

In python, I have a parent process that spawns multiple child processes. I was faced with a situation where, due to an unhandled exception, the parent process was dying, and the child process was processed where it remained an orphan. How to make child processes recognize that they have lost a parent?

I tried code that hooks the child process to every available signal, and none of them were running. I could theoretically put in a giant attempt / exclusion from the parent process to ensure that it at least calls the sigster for the children, but it is inelegant and not flawless. How to prevent orphan processes?

+6
source share
2 answers

You can use socketpair() to create a pair of unix domain sockets before creating a subprocess. Ask the parent to open one end and the other the other. When the parent exits, the end of the connector will be closed. Then the child finds out that he has left, because he can select() / poll() read events from his socket and receive the file at the end.

+5
source

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 only to verify if a given process exists. See the manual for the kill command.

+8
source

Source: https://habr.com/ru/post/886161/


All Articles