How to stop a multiprocess python program after an exception?

I have a Python program that has several processes (currently only 2) and threads (2 per process). I would like to catch every exception and especially close my program purely on Ctrl + c, but I cannot get it to work. Every time an exception occurs, the program stops, but does not close correctly, leaving me with an unusable command line.

What I have tried so far in pseudo-code:

try: for process in processes: process.join() except: pass #Just to suppress error-messages, will be removed later finally: for process in processes: process.terminate() 

But, as I said, no luck. Also note that I am getting an Exception error for both processes, so they are both paused, I suppose?

Maybe I should also mention that most threads are blocked while listening to the channel.

EDIT So I almost made it. I needed to try: each thread and make sure the threads are connected correctly. There is only one drawback when shutting down: Exception KeyboardInterrupt in <module 'threading' from '/usr/lib64/python2.7/threading.pyc'> ignored . This rises in the main theme of the main process. This thread has already completed, that is, it has passed the last line of code.

+7
source share
1 answer

The problem (I hope) is that exceptions occur inside processes that are not in the connections.

I suggest you try wrapping every main process method in a try-except loop. Then specify a flag (for example, an instance of multiprocessing.Value), which the except statement sets to False. Each process could check the value of the flag and stop (clear after itself) if it is set to False.

Please note: if you just stop the process, it will not clear after itself, since it is the same as sending it SIG_TERM.

+1
source

All Articles