Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signal handling in python-daemon

I installed python-daemon and now I'm trying to get the signal handling right. My code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import signal, time, syslog
import daemon

def runDaemon():
    context = daemon.DaemonContext()

    context.signal_map = { signal.SIGTERM: programCleanup }

    context.open()
    with context:
        doMainProgram()

def doMainProgram():
    while True:
        syslog.syslog("pythonDaemon is running")
        time.sleep(5)

def programCleanup():
    syslog.syslog("pythonDaemon STOP")

if __name__ == "__main__":
    runDaemon()

When I start the code everything works as expected: The text pythonDaemon is running gets written to /var/log/syslog every 5 seconds. But when I want to terminate the daemon with kill -TERM *PID* the daemon is terminated but the text pythonDaemon STOP is missing from syslog.

What am I doing wrong?

NB: I am not working with from daemon import runner here, cause that gives me an error (looks like I need an older version of lockfile) and I will not fix this unless it is the only possibilty to get the signal-handling right.

like image 568
Ocaso Protal Avatar asked Jan 18 '14 18:01

Ocaso Protal


People also ask

What are signal handlers Python?

A Signal Handler is a user defined function, where Python signals can be handled. If we take the signal SIGINT (Interrupt Signal), the default behavior would be to stop the current running program. We can, however, assign a signal handler to detect this signal and do our custom processing instead!

How do I run a daemon process in Python?

Daemon processes in Python To execute the process in the background, we need to set the daemonic flag to true. The daemon process will continue to run as long as the main process is executing and it will terminate after finishing its execution or when the main program would be killed.

What is Sigkill in Python?

SIGKILL is where the Python process is terminated by your system. Reasons I have seen this: Low resources (not enough RAM, usually) - monitor and see how much the program is using. You might also want to try explicitly setting n_jobs to a low number, as CPU over-subscription could be an issue.

What is Sigterm in Python?

Python provides the Signal library allowing developers to catch Unix signals and set handlers for asynchronous events. For example, the 'SIGTERM' (Terminate) signal is received when issuing a 'kill' command for a given Unix process.


1 Answers

Your code looks fine, except the signal handler is not called because it has the wrong signature. Make it like this:

def programCleanup(signum, frame):

Quoting the docs (signal.signal()):

The handler is called with two arguments: the signal number and the current stack frame

like image 189
grebneke Avatar answered Sep 17 '22 00:09

grebneke