Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill Child Process if Parent is killed in Python

Tags:

I'm spawning 5 different processes from a python script, like this:

p = multiprocessing.Process(target=some_method,args=(arg,)) p.start() 

My problem is, when, somehow the parent process (the main script) gets killed, the child processes keeps on running.

Is there a way to kill child processes, which are spawned like this, when the parent gets killed ?

EDIT: I'm trying this:

p = multiprocessing.Process(target=client.start,args=(self.query_interval,)) p.start() atexit.register(p.terminate) 

But this doesnt seem to be working

like image 553
Saurabh Verma Avatar asked Aug 28 '14 06:08

Saurabh Verma


People also ask

How do you kill a child process in Python?

You can kill all child processes by first getting a list of all active child processes via the multiprocessing. active_children() function then calling either terminate() or kill() on each process instance.

How do you kill a child's process?

For killing a child process after a given timeout, we can use the timeout command. It runs the command passed to it and kills it with the SIGTERM signal after the given timeout. In case we want to send a different signal like SIGINT to the process, we can use the –signal flag.

What happens to the Childs If you kill a parent process in Linux?

I held a very incorrect assumption about this relationship. I thought that if I kill the parent of a process, it kills the children of that process too. However, this is incorrect. Instead, child processes become orphaned, and the init process re-parents them.

How do you kill a process in python?

A process can be killed by calling the Process. kill() function. The call will only terminate the target process, not child processes.


2 Answers

I've encounter the same problem myself, I've got the following solution:

before calling p.start(), you may set p.daemon=True. Then as mentioned here python.org multiprocessing

When a process exits, it attempts to terminate all of its daemonic child processes.

like image 163
flyingfoxlee Avatar answered Sep 22 '22 16:09

flyingfoxlee


The child is not notified of the death of its parent, it only works the other way.

However, when a process dies, all its file descriptors are closed. And the other end of a pipe is notified about this, if it selects the pipe for reading.

So your parent can create a pipe before spawning the process (or in fact, you can just set up stdin to be a pipe), and the child can select that for reading. It will report ready for reading when the parent end is closed. This requires your child to run a main loop, or at least make regular calls to select. If you don't want that, you'll need some manager process to do it, but then when that one is killed, things break again.

like image 32
Bas Wijnen Avatar answered Sep 23 '22 16:09

Bas Wijnen