Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know when a child process died?

In my class I run 4 process.

from multiprocessing import Process

    procs = (
             Process(target=ClassOne, name='ClassOne'),
             Process(target=ClassTwo, name='ClassTwo'),
             Process(target=ClassThree, name='ClassThree'),
             Process(target=ClassFour, name='ClassFour'),
            )

    for p in procs:
        p.daemon = False
        p.start()

I would like to be notified when one of my children process died so i can kill the other and my self.

like image 606
Spì Avatar asked Sep 09 '10 10:09

Spì


3 Answers

Just define a signal handler for SIGCHLD, inspect the frame returned by the just dead child to retrieve the information you need about it ... and if necessary exit() the parent too :)

like image 119
drAlberT Avatar answered Oct 17 '22 09:10

drAlberT


It is possible to use os.waitpid() passing -1 as the first argument and 0 as the second one.

  • The first argument means that the request pertains to any child of the current process.
  • The second argument means that it behaves as wait().

The function returns a tuple with the pid of the dead child and its exit code.

like image 41
Spì Avatar answered Oct 17 '22 11:10

Spì


You might like to look at the class AutoJoiningProcess in the answer to this similar question.

If you're prepared to add to your code a dependency to gobject (part of PyGTK) then AutoJoiningProcess would allow you can listen to a signal that is emitted when a process finishes. On that signal you could then respond however you'd like.

like image 32
Matthew Walker Avatar answered Oct 17 '22 09:10

Matthew Walker