- 1 year ago
Python multiprocessing - catch SIGINT/SIGTERM and exit gracefully
To catch the SIGINT
and SIGTERM
signals and exit gracefully in a Python multiprocessing program, you can follow these steps:
Import the necessary modules:
pythonimport signal
import sys
import multiprocessing
Define a signal handler function to handle the
SIGINT
andSIGTERM
signals:pythondef signal_handler(signum, frame):
# Perform any necessary cleanup or finalization steps
# before exiting the program gracefully
print("Received signal {}, exiting gracefully...".format(signum))
sys.exit(0)
Register the signal handler function for
SIGINT
andSIGTERM
signals:pythonsignal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
Start your multiprocessing tasks:
pythondef task():
# Your task logic here
pass
if __name__ == "__main__":
# Start the multiprocessing tasks
process = multiprocessing.Process(target=task)
process.start()
process.join()
With this setup, when a SIGINT
or SIGTERM
signal is received, the signal handler function will be called. Inside the signal handler, you can perform any necessary cleanup or finalization steps before exiting the program gracefully.
Note that the signal handler function should be defined at the top level of your script, and the signal.signal()
calls should be placed before starting the multiprocessing tasks.
By implementing signal handling in your Python multiprocessing program, you can catch and respond to SIGINT
(Ctrl+C) and SIGTERM
signals, allowing your program to exit gracefully and perform any necessary cleanup operations before termination.