Home > Article > Backend Development > How to Gracefully Handle SIGTERM Signals in Python?
Gracefully handling SIGTERM signals in Python
When working with long-running Python daemons, handling termination signals such as SIGTERM gracefully is crucial for ensuring a clean shutdown without data loss. This involves the ability to pause the current execution, perform necessary cleanup tasks, and then gracefully terminate the process. Here's how to achieve this:
Using a signal handler
Python provides the signal.signal function to register a handler for a specific signal. By registering a handler for SIGTERM, we can intercept the signal before it terminates the execution. However, as mentioned in the question, the handler still interrupts the current execution and passes control to itself.
Using a separate thread for signal handling
To avoid interrupting the current execution, we can create a separate thread to handle the signal event. This allows us to perform shutdown-related tasks in the background without disrupting the main loop. Here's an example using a simple class:
Solution:
import signal import threading import time class GracefulKiller: kill_now = False def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self, signum, frame): self.kill_now = True def mainloop(): killer = GracefulKiller() while not killer.kill_now: # Perform necessary tasks in the main loop time.sleep(1) print("doing something in a loop ...") if __name__ == '__main__': mainloop() # When the main loop exits, we have gracefully handled the termination signal print("End of the program. I was killed gracefully :)")
In this solution, the GracefulKiller class registers a signal handler for SIGTERM. When the signal is received, the kill_now flag is set to True. The main loop checks this flag and continues until it is True. This allows the main loop to complete any critical tasks before gracefully terminating.
By using a separate thread or class-based solution, we can ensure that the termination signal is handled without prematurely killing the main execution. This approach allows us to perform a graceful shutdown, ensuring data integrity and a clean exit for our daemon.
The above is the detailed content of How to Gracefully Handle SIGTERM Signals in Python?. For more information, please follow other related articles on the PHP Chinese website!