Python exit handlers

1.1k views Asked by At

I'm a bit confused by the many different ways to install exit handlers in Python applications. There's atexit.register() and signal.signal(SIG, handler), but I'm unsure which one is the right to use in my case.

I've got a main process started from the command line which spawns a number of other sub processes as daemons. It then joins the processes and waits until they finish. The sub processes run an infinite loop (can break out by a flag, but not sure how to trigger that). I'd like to call some cleanup code in the sub processes when the main process gets either shut down via CTRL+C or when it receives a kill signal.

What's the best way of achieving this, given the 2 exit handler methods (or perhaps there're more).

1

There are 1 answers

1
AudioBubble On

From the documentation of atexit:

Functions thus registered are automatically executed upon normal interpreter termination.

and

Note: The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.

So if you want to react to signals, use signal.signal.