Maison >développement back-end >Tutoriel Python >Comment gérer gracieusement les signaux SIGTERM dans les démons Python ?
In daemonic operations, terminating a process using SIGTERM (TERM) signal can abruptly interrupt critical tasks. To address this, let's explore how to gracefully handle this signal.
Given a simple daemon written in Python:
def mainloop(): while True: # Perform important jobs # Sleep
daemonizing it using start-stop-daemon sends SIGTERM (TERM) upon termination. If the signal is received during a critical operation (e.g., step #2), it terminates immediately.
Attempts to handle the signal event using signal.signal(signal.SIGTERM, handler) can also interrupt current execution and redirect control to the handler.
To avoid interrupting current execution, we can create a separated thread to handle the TERM signal. This thread can set shutdown_flag = True, allowing the main loop to gracefully exit.
Here's a class-based solution for graceful signal handling:
import signal 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 if __name__ == '__main__': killer = GracefulKiller() while not killer.kill_now: time.sleep(1) print("doing something in a loop ...") print("End of the program. I was killed gracefully :)")
This solution allows the daemon to handle SIGTERM gracefully, ensuring that critical operations can complete before termination. It also provides a clean and maintainable implementation for handling signals in multi-threaded environments.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!