How to Gracefully Handle SIGTERM Signals in Python Daemons?

Patricia Arquette
Release: 2024-11-15 15:56:03
Original
418 people have browsed it

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
Copy after login

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 :)")
Copy after login

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.

The above is the detailed content of How to Gracefully Handle SIGTERM Signals in Python Daemons?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template