Maison > développement back-end > Tutoriel Python > Comment gérer gracieusement les signaux SIGTERM dans les démons Python ?

Comment gérer gracieusement les signaux SIGTERM dans les démons Python ?

Patricia Arquette
Libérer: 2024-11-15 15:56:03
original
574 Les gens l'ont consulté

How to Gracefully Handle SIGTERM Signals in Python Daemons?

Graceful Handling of SIGTERM Signal

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.

Problem Statement

Given a simple daemon written in Python:

def mainloop():
    while True:
        # Perform important jobs
        # Sleep
Copier après la connexion

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.

Using signal.signal()

Attempts to handle the signal event using signal.signal(signal.SIGTERM, handler) can also interrupt current execution and redirect control to the handler.

Solution: Separated Thread for Signal Handling

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.

Implementation

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 :)")
Copier après la connexion

Benefits

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!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal