3
.\" Author: Lennart Poettering <lennart@poettering.net>
4
.\" Generator: DocBook XSL Stylesheets v1.77.1 <http://docbook.sf.net/>
10
.TH "DAEMON" "7" "" "systemd" "daemon"
11
.\" -----------------------------------------------------------------
12
.\" * Define some portability stuff
13
.\" -----------------------------------------------------------------
14
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15
.\" http://bugs.debian.org/507673
16
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
17
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20
.\" -----------------------------------------------------------------
21
.\" * set default formatting
22
.\" -----------------------------------------------------------------
23
.\" disable hyphenation
25
.\" disable justification (adjust text to left margin only)
27
.\" -----------------------------------------------------------------
28
.\" * MAIN CONTENT STARTS HERE *
29
.\" -----------------------------------------------------------------
31
daemon \- Writing and packaging system daemons
34
A daemon is a service process that runs in the background and supervises the system or provides functionality to other processes\&. Traditionally, daemons are implemented following a scheme originating in SysV Unix\&. Modern daemons should follow a simpler yet more powerful scheme (here called "new\-style" daemons), as implemented by
35
\fBsystemd\fR(1)\&. This manual page covers both schemes, and in particular includes recommendations for daemons that shall be included in the systemd init system\&.
38
When a traditional SysV daemon starts, it should execute the following steps as part of the initialization\&. Note that these steps are unnecessary for new\-style daemons (see below), and should only be implemented if compatibility with SysV is essential\&.
48
Close all open file descriptors except STDIN, STDOUT, STDERR (i\&.e\&. the first three file descriptors 0, 1, 2)\&. This ensures that no accidentally passed file descriptor stays around in the daemon process\&. On Linux this is best implemented by iterating through
49
/proc/self/fd, with a fallback of iterating from file descriptor 3 to the value returned by
62
Reset all signal handlers to their default\&. This is best done by iterating through the available signals up to the limit of _NSIG and resetting them to SIG_DFL\&.
73
Reset the signal mask using
74
\fBsigprocmask()\fR\&.
85
Sanitize the environment block, removing or resetting environment variables that might negatively impact daemon runtime\&.
97
\fBfork()\fR, to create a background process\&.
110
to detach from any terminal and create an independent session\&.
123
again, to ensure the daemon can never re\-acquire a terminal again\&.
136
in the first child, so that only the second child (the actual daemon process) stays around\&. This ensures that the daemon process is re\-parented to init/PID 1, as all daemons should be\&.
147
In the daemon process, connect
149
to STDIN, STDOUT, STDERR\&.
160
In the daemon process, reset the umask to 0, so that the file modes passed to
163
and suchlike directly control the access mode of the created files and directories\&.
174
In the daemon process, change the current directory to the root directory (/), in order to avoid that the daemon involuntarily blocks mount points from being unmounted\&.
185
In the daemon process, write the daemon PID (as returned by
186
\fBgetpid()\fR) to a PID file, for example
187
/var/run/foobar\&.pid
188
(for a hypothetical daemon "foobar"), to ensure that the daemon cannot be started more than once\&. This must be implemented in race\-free fashion so that the PID file is only updated when at the same time it is verified that the PID previously stored in the PID file no longer exists or belongs to a foreign process\&. Commonly some kind of file locking is employed to implement this logic\&.
199
In the daemon process, drop privileges, if possible and applicable\&.
210
From the daemon process notify the original process started that initialization is complete\&. This can be implemented via an unnamed pipe or similar communication channel that is created before the first
212
and hence available in both the original and the daemon process\&.
225
in the original process\&. The process that invoked the daemon must be able to rely on that this
227
happens after initialization is complete and all external communication channels are established and accessible\&.
232
function should not be used, as it implements only a subset of these steps\&.
234
A daemon that needs to provide compatibility with SysV systems should implement the scheme pointed out above\&. However, it is recommended to make this behavior optional and configurable via a command line argument, to ease debugging as well as to simplify integration into systems using systemd\&.
235
.SS "New\-Style Daemons"
237
Modern services for Linux should be implemented as new\-style daemons\&. This makes it easier to supervise and control them at runtime and simplifies their implementation\&.
239
For developing a new\-style daemon none of the initialization steps recommended for SysV daemons need to be implemented\&. New\-style init systems such as systemd make all of them redundant\&. Moreover, since some of these steps interfere with process monitoring, file descriptor passing and other functionality of the init system it is recommended not to execute them when run as new\-style service\&.
241
Note that new\-style init systems guarantee execution of daemon processes in clean process contexts: it is guaranteed that the environment block is sanitized, that the signal handlers and mask is reset and that no left\-over file descriptors are passed\&. Daemons will be executed in their own session, and STDIN/STDOUT/STDERR connected to
243
unless otherwise configured\&. The umask is reset\&.
245
It is recommended for new\-style daemons to implement the following:
255
If SIGTERM is received, shut down the daemon and exit cleanly\&.
266
If SIGHUP is received, reload the configuration files, if this applies\&.
277
Provide a correct exit code from the main daemon process, as this is used by the init system to detect service errors and problems\&. It is recommended to follow the exit code scheme as defined in the
278
\m[blue]\fBLSB recommendations for SysV init scripts\fR\m[]\&\s-2\u[1]\d\s+2\&.
289
If possible and applicable expose the daemon\*(Aqs control interface via the D\-Bus IPC system and grab a bus name as last step of initialization\&.
300
For integration in systemd, provide a
302
unit file that carries information about starting, stopping and otherwise maintaining the daemon\&. See
303
\fBsystemd.service\fR(5)
315
As much as possible, rely on the init system\*(Aqs functionality to limit the access of the daemon to files, services and other resources\&. i\&.e\&. in the case of systemd, rely on systemd\*(Aqs resource limit control instead of implementing your own, rely on systemd\*(Aqs privilege dropping code instead of implementing it in the daemon, and similar\&. See
316
\fBsystemd.exec\fR(5)
317
for the available controls\&.
328
If D\-Bus is used, make your daemon bus\-activatable, via supplying a D\-Bus service activation configuration file\&. This has multiple advantages: your daemon may be started lazily on\-demand; it may be started in parallel to other daemons requiring it \-\- which maximizes parallelization and boot\-up speed; your daemon can be restarted on failure, without losing any bus requests, as the bus queues requests for activatable services\&. See below for details\&.
339
If your daemon provides services to other local processes or remote clients via a socket, it should be made socket\-activatable following the scheme pointed out below\&. Like D\-Bus activation this enables on\-demand starting of services as well as it allows improved parallelization of service start\-up\&. Also, for state\-less protocols (such as syslog, DNS) a daemon implementing socket\-based activation can be restarted without losing a single request\&. See below for details\&.
350
If applicable a daemon should notify the init system about startup completion or status updates via the
365
call to log directly to the system syslog service, a new\-style daemon may choose to simply log to STDERR via
366
\fBfprintf()\fR, which is then forwarded to syslog by the init system\&. If log priorities are necessary these can be encoded by prefixing individual log lines with strings like "<4>" (for log priority 4 "WARNING" in the syslog priority scheme), following a similar style as the Linux kernel\*(Aqs
368
priority system\&. In fact, using this style of logging also enables the init system to optionally direct all application logging to the kernel log buffer (kmsg), as accessible via
369
\fBdmesg\fR(1)\&. This kind of logging may be enabled by setting
370
\fIStandardError=syslog\fR
371
in the service unit file\&. For details see
374
\fBsystemd.exec\fR(5)\&.
377
These recommendations are similar but not identical to the
378
\m[blue]\fBApple MacOS X Daemon Requirements\fR\m[]\&\s-2\u[2]\d\s+2\&.
381
New\-style init systems provide multiple additional mechanisms to activate services, as detailed below\&. It is common that services are configured to be activated via more than one mechanism at the same time\&. An example for systemd:
383
might get activated either when Bluetooth hardware is plugged in, or when an application accesses its programming interfaces via D\-Bus\&. Or, a print server daemon might get activated when traffic arrives at an IPP port, or when a printer is plugged in, or when a file is queued in the printer spool directory\&. Even for services that are intended to be started on system bootup unconditionally it is a good idea to implement some of the various activation schemes outlined below, in order to maximize parallelization: if a daemon implements a D\-Bus service or listening socket, implementing the full bus and socket activation scheme allows starting of the daemon with its clients in parallel (which speeds up boot\-up), since all its communication channels are established already, and no request is lost because client requests will be queued by the bus system (in case of D\-Bus) or the kernel (in case of sockets), until the activation is completed\&.
384
.SS "Activation on Boot"
386
Old\-style daemons are usually activated exclusively on boot (and manually by the administrator) via SysV init scripts, as detailed in the
387
\m[blue]\fBLSB Linux Standard Base Core Specification\fR\m[]\&\s-2\u[1]\d\s+2\&. This method of activation is supported ubiquitously on Linux init systems, both old\-style and new\-style systems\&. Among other issues SysV init scripts have the disadvantage of involving shell scripts in the boot process\&. New\-style init systems generally employ updated versions of activation, both during boot\-up and during runtime and using more minimal service description files\&.
389
In systemd, if the developer or administrator wants to make sure a service or other unit is activated automatically on boot it is recommended to place a symlink to the unit file in the
394
graphical\&.target, which are normally used as boot targets at system startup\&. See
395
\fBsystemd.unit\fR(5)
396
for details about the
399
\fBsystemd.special\fR(7)
400
for details about the two boot targets\&.
401
.SS "Socket\-Based Activation"
403
In order to maximize the possible parallelization and robustness and simplify configuration and development, it is recommended for all new\-style daemons that communicate via listening sockets to employ socket\-based activation\&. In a socket\-based activation scheme the creation and binding of the listening socket as primary communication channel of daemons to local (and sometimes remote) clients is moved out of the daemon code and into the init system\&. Based on per\-daemon configuration the init system installs the sockets and then hands them off to the spawned process as soon as the respective daemon is to be started\&. Optionally activation of the service can be delayed until the first inbound traffic arrives at the socket, to implement on\-demand activation of daemons\&. However, the primary advantage of this scheme is that all providers and all consumers of the sockets can be started in parallel as soon as all sockets are established\&. In addition to that daemons can be restarted with losing only a minimal number of client transactions or even any client request at all (the latter is particularly true for state\-less protocols, such as DNS or syslog), because the socket stays bound and accessible during the restart, and all requests are queued while the daemon cannot process them\&.
405
New\-style daemons which support socket activation must be able to receive their sockets from the init system, instead of creating and binding them themselves\&. For details about the programming interfaces for this scheme provided by systemd see
406
\fBsd_listen_fds\fR(3)
408
\fBsd-daemon\fR(3)\&. For details about porting existing daemons to socket\-based activation see below\&. With minimal effort it is possible to implement socket\-based activation in addition to traditional internal socket creation in the same codebase in order to support both new\-style and old\-style init systems from the same daemon binary\&.
410
systemd implements socket\-based activation via
412
units, which are described in
413
\fBsystemd.socket\fR(5)\&. When configuring socket units for socket\-based activation it is essential that all listening sockets are pulled in by the special target unit
414
sockets\&.target\&. It is recommended to place a
415
\fIWantedBy=sockets\&.target\fR
418
section, to automatically add such a dependency on installation of a socket unit\&. Unless
419
\fIDefaultDependencies=no\fR
420
is set the necessary ordering dependencies are implicitly created for all socket units\&. For more information about
423
\fBsystemd.special\fR(7)\&. It is not necessary or recommended to place any additional dependencies on socket units (for example from
425
or suchlike) when one is installed in
427
.SS "Bus\-Based Activation"
429
When the D\-Bus IPC system is used for communication with clients, new\-style daemons should employ bus activation so that they are automatically activated when a client application accesses their IPC interfaces\&. This is configured in D\-Bus service files (not to be confused with systemd service unit files!)\&. To ensure that D\-Bus uses systemd to start\-up and maintain the daemon use the
430
\fISystemdService=\fR
431
directive in these service files, to configure the matching systemd service for a D\-Bus service\&. e\&.g\&.: for a D\-Bus service whose D\-Bus activation file is named
432
org\&.freedesktop\&.RealtimeKit\&.service, make sure to set
433
\fISystemdService=rtkit\-daemon\&.service\fR
434
in that file, to bind it to the systemd service
435
rtkit\-daemon\&.service\&. This is needed to make sure that the daemon is started in a race\-free fashion when activated via multiple mechanisms simultaneously\&.
436
.SS "Device\-Based Activation"
438
Often, daemons that manage a particular type of hardware should be activated only when the hardware of the respective kind is plugged in or otherwise becomes available\&. In a new\-style init system it is possible to bind activation to hardware plug/unplug events\&. In systemd, kernel devices appearing in the sysfs/udev device tree can be exposed as units if they are tagged with the string "systemd"\&. Like any other kind of unit they may then pull in other units when activated (i\&.e\&. Plugged in) and thus implement device\-based activation\&. Systemd dependencies may be encoded in the udev database via the
441
\fBsystemd.device\fR(5)
442
for details\&. Often it is nicer to pull in services from devices only indirectly via dedicated targets\&. Example: instead of pulling in
444
from all the various bluetooth dongles and other hardware available, pull in bluetooth\&.target from them and
446
from that target\&. This provides for nicer abstraction and gives administrators the option to enable
449
bluetooth\&.target\&.wants/
450
symlink uniformly with a command like
454
instead of manipulating the udev ruleset\&.
455
.SS "Path\-Based Activation"
457
Often, runtime of daemons processing spool files or directories (such as a printing system) can be delayed until these file system objects change state, or become non\-empty\&. New\-style init systems provide a way to bind service activation to file system changes\&. systemd implements this scheme via path\-based activation configured in
459
units, as outlined in
460
\fBsystemd.path\fR(5)\&.
461
.SS "Timer\-Based Activation"
463
Some daemons that implement clean\-up jobs that are intended to be executed in regular intervals benefit from timer\-based activation\&. In systemd, this is implemented via
465
units, as described in
466
\fBsystemd.timer\fR(5)\&.
467
.SS "Other Forms of Activation"
469
Other forms of activation have been suggested and implemented in some systems\&. However, often there are simpler or better alternatives, or they can be put together of combinations of the schemes above\&. Example: sometimes it appears useful to start daemons or
471
units when a specific IP address is configured on a network interface, because network sockets shall be bound to the address\&. However, an alternative to implement this is by utilizing the Linux IP_FREEBIND socket option, as accessible via
473
in systemd socket files (see
474
\fBsystemd.socket\fR(5)
475
for details)\&. This option, when enabled, allows sockets to be bound to a non\-local, not configured IP address, and hence allows bindings to a particular IP address before it actually becomes available, making such an explicit dependency to the configured address redundant\&. Another often suggested trigger for service activation is low system load\&. However, here too, a more convincing approach might be to make proper use of features of the operating system: in particular, the CPU or IO scheduler of Linux\&. Instead of scheduling jobs from userspace based on monitoring the OS scheduler, it is advisable to leave the scheduling of processes to the OS scheduler itself\&. systemd provides fine\-grained access to the CPU and IO schedulers\&. If a process executed by the init system shall not negatively impact the amount of CPU or IO bandwidth available to other processes, it should be configured with
476
\fICPUSchedulingPolicy=idle\fR
478
\fIIOSchedulingClass=idle\fR\&. Optionally, this may be combined with timer\-based activation to schedule background jobs during runtime and with minimal impact on the system, and remove it from the boot phase itself\&.
479
.SH "INTEGRATION WITH SYSTEMD"
480
.SS "Writing Systemd Unit Files"
482
When writing systemd unit files, it is recommended to consider the following suggestions:
492
If possible do not use the
494
setting in service files\&. But if you do, make sure to set the PID file path using
495
\fIPIDFile=\fR\&. See
496
\fBsystemd.service\fR(5)
508
If your daemon registers a D\-Bus name on the bus, make sure to use
510
in the service file if possible\&.
521
Make sure to set a good human\-readable description string with
522
\fIDescription=\fR\&.
534
\fIDefaultDependencies=\fR, unless you really know what you do and your unit is involved in early boot or late system shutdown\&.
545
Normally, little if any dependencies should need to be defined explicitly\&. However, if you do configure explicit dependencies, only refer to unit names listed on
546
\fBsystemd.special\fR(7)
547
or names introduced by your own package to keep the unit file operating system\-independent\&.
558
Make sure to include an
560
section including installation information for the unit file\&. See
561
\fBsystemd.unit\fR(5)
562
for details\&. To activate your service on boot make sure to add a
563
\fIWantedBy=multi\-user\&.target\fR
565
\fIWantedBy=graphical\&.target\fR
566
directive\&. To activate your socket on boot, make sure to add
567
\fIWantedBy=sockets\&.target\fR\&. Usually you also want to make sure that when your service is installed your socket is installed too, hence add
568
\fIAlso=foo\&.socket\fR
570
foo\&.service, for a hypothetical program
573
.SS "Installing Systemd Service Files"
575
At the build installation time (e\&.g\&.
577
during package build) packages are recommended to install their systemd unit files in the directory returned by
578
\fBpkg\-config systemd \-\-variable=systemdsystemunitdir\fR
579
(for system services) or
580
\fBpkg\-config systemd \-\-variable=systemduserunitdir\fR
581
(for user services)\&. This will make the services available in the system on explicit request but not activate them automatically during boot\&. Optionally, during package installation (e\&.g\&.
583
by the administrator) symlinks should be created in the systemd configuration directories via the
587
tool, to activate them automatically on boot\&.
591
are recommended to use a configure script excerpt like the following to determine the unit installation path during source configuration:
598
AC_ARG_WITH([systemdsystemunitdir],
599
AS_HELP_STRING([\-\-with\-systemdsystemunitdir=DIR], [Directory for systemd service files]),
600
[], [with_systemdsystemunitdir=$($PKG_CONFIG \-\-variable=systemdsystemunitdir systemd)])
601
if test "x$with_systemdsystemunitdir" != xno; then
602
AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])
604
AM_CONDITIONAL(HAVE_SYSTEMD, [test \-n "$with_systemdsystemunitdir" \-a "x$with_systemdsystemunitdir" != xno ])
610
This snippet allows automatic installation of the unit files on systemd machines, and optionally allows their installation even on machines lacking systemd\&. (Modification of this snippet for the user unit directory is left as an exercise for the reader\&.)
612
Additionally, to ensure that
614
continues to work, it is recommended to add the following to the top\-level
617
\fBautomake\fR(1)\-based projects:
623
DISTCHECK_CONFIGURE_FLAGS = \e
624
\-\-with\-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)
630
Finally, unit files should be installed in the system with an automake excerpt like the following:
637
systemdsystemunit_DATA = \e
649
file use snippets like the following to enable/disable the service during installation/deinstallation\&. This makes use of the RPM macros shipped along systemd\&. Consult the packaging guidelines of your distribution for details and the equivalent for other package managers\&.
651
At the top of the file:
657
BuildRequires: systemd
664
And as scriptlets, further down:
671
%systemd_post foobar\&.service foobar\&.socket
674
%systemd_preun foobar\&.service foobar\&.socket
683
If the service shall be restarted during upgrades replace the
685
scriptlet above with the following:
692
%systemd_postun_with_restart foobar\&.service
702
expect the names of all units that are installed/removed as arguments, separated by spaces\&.
704
expects no arguments\&.
705
%systemd_postun_with_restart
706
expects the units to restart as arguments\&.
708
To facilitate upgrades from a package version that shipped only SysV init scripts to a package version that ships both a SysV init script and a native systemd service file, use a fragment like the following:
714
%triggerun \-\- foobar < 0\&.47\&.11\-1
715
if /sbin/chkconfig \-\-level 5 foobar ; then
716
/bin/systemctl \-\-no\-reload enable foobar\&.service foobar\&.socket >/dev/null 2>&1 || :
723
Where 0\&.47\&.11\-1 is the first package version that includes the native unit file\&. This fragment will ensure that the first time the unit file is installed it will be enabled if and only if the SysV init script is enabled, thus making sure that the enable status is not changed\&. Note that
725
is a command specific to Fedora which can be used to check whether a SysV init script is enabled\&. Other operating systems will have to use different commands here\&.
726
.SH "PORTING EXISTING DAEMONS"
728
Since new\-style init systems such as systemd are compatible with traditional SysV init systems it is not strictly necessary to port existing daemons to the new style\&. However doing so offers additional functionality to the daemons as well as simplifying integration into new\-style init systems\&.
730
To port an existing SysV compatible daemon the following steps are recommended:
740
If not already implemented, add an optional command line switch to the daemon to disable daemonization\&. This is useful not only for using the daemon in new\-style init systems, but also to ease debugging\&.
751
If the daemon offers interfaces to other software running on the local system via local AF_UNIX sockets, consider implementing socket\-based activation (see above)\&. Usually a minimal patch is sufficient to implement this: Extend the socket creation in the daemon code so that
752
\fBsd_listen_fds\fR(3)
753
is checked for already passed sockets first\&. If sockets are passed (i\&.e\&. when
754
\fBsd_listen_fds()\fR
755
returns a positive value), skip the socket creation step and use the passed sockets\&. Secondly, ensure that the file\-system socket nodes for local AF_UNIX sockets used in the socket\-based activation are not removed when the daemon shuts down, if sockets have been passed\&. Third, if the daemon normally closes all remaining open file descriptors as part of its initialization, the sockets passed from the init system must be spared\&. Since new\-style init systems guarantee that no left\-over file descriptors are passed to executed processes, it might be a good choice to simply skip the closing of all remaining open file descriptors if sockets are passed\&.
766
Write and install a systemd unit file for the service (and the sockets if socket\-based activation is used, as well as a path unit file, if the daemon processes a spool directory), see above for details\&.
777
If the daemon exposes interfaces via D\-Bus, write and install a D\-Bus activation file for the service, see above for details\&.
784
\fBsd_listen_fds\fR(3),
787
\fBsystemd.service\fR(5)
790
LSB recommendations for SysV init scripts
792
\%http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
795
Apple MacOS X Daemon Requirements
797
\%http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/LaunchOnDemandDaemons.html#//apple_ref/doc/uid/TP40001762-104738