- 1 year ago
atexit handler not responding to signals
The atexit
module in Python is used to register functions to be called when the program is about to exit. However, atexit
handlers might not respond to signals like SIGTERM
or SIGINT
because these signals can abruptly terminate the program without giving the registered atexit
handlers a chance to run.
To handle signals like SIGTERM
and SIGINT
along with atexit
handlers, you need to use a combination of techniques. Here's how you can do it:
pythonimport signal
import atexit
def exit_handler():
print("Exiting...")
def sigterm_handler(signum, frame):
print("SIGTERM received")
exit_handler()
exit(1)
def sigint_handler(signum, frame):
print("SIGINT received")
exit_handler()
exit(1)
atexit.register(exit_handler)
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigint_handler)
print("Running...")
input("Press Enter to simulate normal exit: ")
In this example, we've defined an exit_handler
function to print a message when the program exits. We've also defined sigterm_handler
and sigint_handler
functions to respond to SIGTERM
and SIGINT
signals. These signal handlers call the exit_handler
function before exiting the program.
Keep in mind that some signals cannot be caught or handled, such as SIGKILL
, which forces the termination of a process. However, the combination of atexit
handlers and signal handlers can help you manage graceful shutdowns and cleanup tasks before the program exits due to signals.