4

I noticed that os._exit(<num>) ::

Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.

and that sys.exit() ::

“only” raises an exception, it will only exit the process when called from the main thread

I need a solution to close a multi-processed application that will ensure all processes are closed (none left orphaned) and that it exits in the best state possible.

Extras:

I am creating the processes using the python multiprocessing library, by creating classes which inherit from multiprocessing.Process

Matt Seymour
  • 8,880
  • 7
  • 60
  • 101
  • see this question http://stackoverflow.com/questions/5849484/how-to-exit-a-multithreaded-program – jbaldwin Nov 12 '12 at 11:14
  • 1
    Thanks @jbaldwin this is dealing with threading which is different to multiprocessing. Threads will be killed with the main thread being terminated where-as with multiprocessing you can end up with child processes persisting. – Matt Seymour Nov 12 '12 at 11:17
  • How do you create the processes? If you create them with `subprocess`, then you can call [`Popen.terminate()`](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.terminate) to kill all the children processes and then exit using `sys.exit`. If you are in a child process you can send a message to the main thread to do this for you. – Bakuriu Nov 12 '12 at 14:02
  • @Bakuriu I create the process by extending the python multiprocessing.process classes – Matt Seymour Dec 06 '12 at 16:23

1 Answers1

1

I ended up creating a Pipe for every Process. Then when the main Process shuts down it can send a message to all the children Processes that they should shut down too.

In order to make that work right you've got to put a periodic check into the children Processes' "do loop" to see if there are messages in the pipe, and if so, check them to see if it's a "quit now" message.

Mike Sandford
  • 1,315
  • 10
  • 22