Writing the right daemon in Python is difficult. In fact, it is difficult in any language. PEP 3143 explains the problems.
The daemon module wraps most of the details, so you donβt need to fix them. If you use this, itβs very easy to add a cleanup code.
One option is to simply subclass daemon.DaemonContext and put it there. For instance:
class MyDaemonContext(daemon.DaemonContext): def close(self): if not self.is_open: return prevent_the_apocalypse() super(MyDaemonContext, self).close() with MyDaemonContext(): while True: give_high_fives()
The daemon module already installs signal handlers to do what you configured them, but without missing the close method. ( close will be executed exactly once - in the context of __exit__ , in the atexit method or, possibly, in another place.)
If you need something more complicated, where some signals skip close and others don't, just set its signal_map appropriately instead of a subclass.
source share