Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top