Writing a well-behaved daemon

Ben Finney ben at benfinney.id.au
Fri Sep 26 07:08:33 CEST 2008


Howdy all,

Writing a Python program to become a Unix daemon is relatively
well-documented: there's a recipe for detaching the process and
running in its own process group. However, there's much more to a Unix
daemon than simply detaching. At a minimum, a well-behaved Unix daemon
must at least:

* Detach the process into its own process group

* Close stdin, redirect stdout and stderr to a null device

* Handle its own PID file: refuse to start if the PID file already
  exists, write the PID file on startup otherwise, and remove the PID
  file on termination

* Revoke setuid and setgid privileges, which are strongly deprecated
  these days

* Handle interrupts, cleaning up the process and PID file as necessary

* (possible others)

There are also many other commonly-expected tasks that well-behaved
Unix daemons perform (drop privileges to a nominated non-root user and
group after daemonising, redirect output to syslog instead, operate in
a chroot jail, respawn when terminated, etc.).

All of this stuff has been done numerous times before, and the basics
are mostly agreed upon. Yet all of these are tricky to implement
correctly, and tedious to re-implement in every program intended to
run as a daemon.


The 'daemon' program <URL:http://www.libslack.org/daemon/> covers all
these, and allows an arbitrary process to be started as a well-behaved
Unix daemon process. It's not a good assumption that this program is
installed on an arbitrary system though, and it seems excessive to ask
the recipient of one's program to get a third-party program just in
order to make a daemon process.

I'd love to be able to have something similar for Python programs,
e.g. a 'become_well_behaved_daemon()' function that implements all the
above and perhaps takes optional arguments for the optional features.

My searches for such functionality haven't borne much fruit though.
Apart from scattered recipes, none of which cover all the essentials
(let alone the optional features) of 'daemon', I can't find anything
that could be relied upon. This is surprising, since I'd expect this
in Python's standard library.

Can anyone point me to the equivalent of the 'daemon' program in the
form of a well-tested Python library?

-- 
 \     “Tis more blessed to give than to receive; for example, wedding |
  `\                                      presents.” —Henry L. Mencken |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list