Significant changes: new section “Other daemon implementations” with brief descriptions of their relationship to this PEP.
:PEP: XXX :Title: Standard daemon process library :Version: 0.2 :Last-Modified: 2009-01-27 11:28 :Author: Ben Finney firstname.lastname@example.org :Status: Draft :Type: Standards Track :Content-Type: text/x-rst :Created: 2009-01-26 :Python-Version: 3.1 :Post-History:
Writing a program to become a well-behaved Unix daemon is somewhat complex and tricky to get right, yet the steps are largely similar for any daemon regardless of what else the program may need to do.
This PEP introduces a module to the Python standard library that provides a simple interface to the task of becoming a daemon process.
Table of Contents:
Correct daemon behaviour
Other daemon implementations
Simple example of usage::
import daemon from spam import do_main_program this_daemon = daemon.Daemon() this_daemon.start() do_main_program()
More complex example usage::
import os import grp import signal import daemon from spam import ( initial_program_setup, do_main_program, program_cleanup, reload_program_config, ) initial_program_setup() important_file = open('spam.data', 'w') interesting_file = open('eggs.data', 'w') this_daemon = daemon.Daemon() this_daemon.files_preserve = [important_file, interesting_file] this_daemon.working_directory = '/var/lib/foo' this_daemon.umask = 0o002 mail_gid = grp.getgrnam('mail').gr_gid this_daemon.gid = mail_gid this_daemon.terminate_callback = program_cleanup this_daemon.reload_callback = reload_program_config this_daemon.reload_signals = [signal.SIGHUP, signal.SIGUSR1] this_daemon.start() do_main_program()
A new module,
daemon, is added to the standard library.
The module defines a class,
Daemon, used to represent the settings
for a daemon process.
An exception class,
DaemonError, is defined for exceptions raised
from the module.
Daemon instance represents the behaviour settings for the process
when it becomes a daemon. The behaviour is customised by setting
attributes on the instance, before calling the
The following attributes are defined.
List of files that should *not* be closed when starting the daemon. If ``None``, all open file descriptors will be closed. Elements of the list are file descriptors (as returned by a file object's `fileno()` method) or Python `file` objects. Each specifies a file that is not to be closed during daemon start.
Full path to a directory to set as the effective root directory of the process. If ``None``, specifies that the root directory is not to be changed.
Full path of the working directory to which the process should change on daemon start. Since a filesystem cannot be unmounted if a process has its current working directory on that filesystem, this should either be left at default or set to a directory that is a sensible “home directory” for the daemon while it is running.
Absolute directory path to contain the daemon's lockfile. If ``None``, the lockfile behaviour for this daemon is skipped.
Base name of the lockfile for this daemon, without directory or suffix. If ``None``, the name is derived from the process command line.
File access creation mask (“umask”) to set for the process on daemon start. Since a process inherits its umask from its parent process, starting the daemon will reset the umask to this value so that files are created by the daemon with access modes as it expects.
[signal.SIGTTOU, signal.SIGTTIN, signal.SIGTSTP]
List of signals that the process should ignore (by setting the signal action to ``signal.SIG_IGN``) on daemon start.
List of signals that the process should interpret as a request to terminate cleanly.
Callable to invoke when the process receives any of the `terminate_signals` signals, before then terminating the process.
List of signals that the process should interpret as a request to reload runtime configuration.
Callable to invoke when the process receives any of the `reload_signals` signals.
The user ID (“uid”) value to switch the process to on daemon start.
The group ID (“gid”) value to switch the process to on daemon start.
If true, prevents the generation of core files, in order to avoid leaking sensitive information from daemons run as `root`.
File-like object, open for writing (in append mode, 'w+'), that will be used as the new value of `sys.stdout`. If it represents an actual file, it should be listed in `files_preserve` to prevent it being closed during daemon start. If ``None``, then `sys.stdout` is not re-bound.
File-like object, open for writing (in append mode, 'w+'), that will be used as the new value of `sys.stderr`. If it represents an actual file, it should be listed in `files_preserve` to prevent it being closed during daemon start. If ``None``, then `sys.stderr` is not re-bound.
The following methods are defined.
Start the daemon. This performs the following steps: * If the `chroot_directory` attribute is not ``None``: * Set the effective root directory of the process to that directory (via `os.chroot`). This allows running the daemon process inside a “chroot gaol” as a means of limiting the system's exposure to rogue behaviour by the process. * If the `lockfile_directory` attribute is not ``None``: * Look in that directory for a file named '`lockfile_name`.pid'; if it exists, raise a `DaemonError` to prevent multiple instances of the daemon process. * Close all open file descriptors, excluding those listed in the `files_preserve` attribute. * Change current working directory to the path specified by the `working_directory` attribute. * Reset the file access creation mask to the value specified by the `umask` attribute. * Detach the current process into its own process group, and disassociate from any controlling terminal. This step is skipped if it is determined to be redundant: if the process was started by `init`, by `initd`, or by `inetd`. * Set signal handlers as specified by the `ignore_signals`, `terminate_signals`, `reload_signals` attributes. * If the `prevent_core` attribute is true: * Set the resource limits for the process to prevent any core dump from the process. * Set the process uid and gid to the true uid and gid of the process, to relinquish any elevated privilege. * If the `lockfile_directory` attribute is not ``None``: * Create the lockfile for this daemon in that directory, by writing a text line containing the current process ID (“pid”) to a file named '`lockfile_name`.pid'. * If either of the attributes `uid` or `gid` are not ``None``: * Set the process uid and/or gid to the specified values. * If either of the attributes `stdout` or `stderr` are not ``None``: * Bind the names `sys.stdout` and/or `sys.stderr` to the corresponding objects.
Reload the daemon configuration. The meaning of this is entirely defined by the customisation of this daemon: if the `reload_callback` attribute is not ``None``, call that object. The return value is discarded.
Stop the daemon. This performs the following steps: * If the `terminate_callback` attribute is not ``None``: * Call that object. The return value is discarded. * If the `lockfile_directory` attribute is not ``None``: * Delete the lockfile for this daemon. * Raise a `SystemExit` exception.
DaemonError class inherits from
Exception. The module
implementation will raise an instance of
DaemonError when an error
occurs in processing daemon behaviour.
The majority of programs written to be Unix daemons either implement
behaviour very similar to that in the
Specification_, or are
poorly-behaved daemons by the
Correct daemon behaviour_.
Since these steps should be much the same in most implementations but are very particular and easy to omit or implement incorrectly, they are a prime target for a standard well-tested implementation in the standard library.
According to Stevens in [stevens]_ §2.6, a program should perform the following steps to become a Unix daemon process.
Close all open file descriptors.
Change current working directory.
Reset the file access creation mask.
Run in the background.
Disassociate from process group.
Ignore terminal I/O signals.
Disassociate from control terminal.
Don't reacquire a control terminal.
Correctly handle the following circumstances:
Started by System V
Daemon termination by
daemon tool [slack-daemon]_ lists (in its summary of features)
behaviour that should be performed when turning a program into a
well-behaved Unix daemon process. It differs from this PEP's intent in
that it invokes a separate program as a daemon process. The
following features are appropriate for a daemon that starts itself
once the program is already running:
Sets up the correct process context for a daemon.
Behaves sensibly when started by
Revokes any suid or sgid privileges to reduce security risks in case daemon is incorrectly installed with special privileges.
Prevents the generation of core files to prevent leaking sensitive information from daemons run as root (optional).
Names the daemon by creating and locking a PID file to guarantee that only one daemon with the given name can execute at any given time (optional).
Sets the user and group under which to run the daemon (optional, root only).
Creates a chroot gaol (optional, root only).
Captures the daemon's stdout and stderr and directs them to syslog (optional).
python-daemon package [python-daemon]_.
As of 2009-01-26, the package is under active development and is not yet a full implementation of this PEP.
Prior to this PEP, several existing third-party Python libraries or
tools implemented some of this PEP's
correct daemon behaviour_.
reference implementation_ is a fairly direct successor from the
Many good ideas were contributed by the community to Python cookbook recipe 66012 [cookbook-66012]_.
bda.daemon library [bda.daemon]_ is an implementation (by
Robert Niederreiter et al) of [cookbook-66012]_. It is the
predecessor of [python-daemon]_.
Other Python daemon implementations that differ from this PEP:
zdaemon tool [zdaemon]_ was written for
the Zope project. Like [slack-daemon]_, it differs from this
specification because it is used to run another program as a daemon
The Python library
daemon [clapper-daemon]_ is (according to its
homepage) no longer maintained. As of version 1.0.1, it implements
the basic steps from [stevens]_.
daemonize library [seutter-daemonize]_ also implements the
basic steps from [stevens]_.
Twisted [twisted]_ includes, perhaps unsurprisingly, an implementation of a process daemonisation API that is integrated with the rest of the Twisted framework; it differs significantly from the API in this PEP.
initd library [dagitses-initd]_, which uses
[clapper-daemon]_, implements an equivalent of Unix
controlling a daemon process.
`Unix Network Programming`, W. Richard Stevens, 1994 Prentice Hall.
The (non-Python) “libslack” implementation of a `daemon` tool `<http://www.libslack.org/daemon/>`_ by “raf” <email@example.com>.
The `python-daemon` library `<http://pypi.python.org/pypi/python-daemon/>`_ by Ben Finney et al.
Python Cookbook recipe 66012, “Fork a daemon process on Unix” `<http://code.activestate.com/recipes/66012/>`_.
The `bda.daemon` library `<http://pypi.python.org/pypi/bda.daemon/>`_ by Robert Niederreiter et al.
The `zdaemon` tool `<http://pypi.python.org/pypi/zdaemon/>`_ by Guido van Rossum et al.
The `daemon` library `<http://pypi.python.org/pypi/daemon/>`_ by Brian Clapper.
The `daemonize` library `<http://daemonize.sourceforge.net/>`_ by Jerry Seutter.
The `Twisted` application framework `<http://pypi.python.org/pypi/Twisted/>`_ by Glyph Lefkowitz et al.
The Python `initd` library `<http://pypi.python.org/pypi/initd/>`_ by Michael Andreas Dagitses.
This work is hereby placed in the public domain. To the extent that placing a work in the public domain is not legally possible, the copyright holder hereby grants to all recipients of this work all rights and freedoms that would otherwise be restricted by copyright.
-- \ “I went to a garage sale. ‘How much for the garage?’ ‘It's not | `\ for sale.’” —Steven Wright | _o__) | Ben Finney