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.
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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With