1DAEMON(7)                           daemon                           DAEMON(7)
2
3
4

NAME

6       daemon - Writing and packaging system daemons
7

DESCRIPTION

9       A daemon is a service process that runs in the background and
10       supervises the system or provides functionality to other processes.
11       Traditionally, daemons are implemented following a scheme originating
12       in SysV Unix. Modern daemons should follow a simpler yet more powerful
13       scheme (here called "new-style" daemons), as implemented by systemd(1).
14       This manual page covers both schemes, and in particular includes
15       recommendations for daemons that shall be included in the systemd init
16       system.
17
18   SysV Daemons
19       When a traditional SysV daemon starts, it should execute the following
20       steps as part of the initialization. Note that these steps are
21       unnecessary for new-style daemons (see below), and should only be
22       implemented if compatibility with SysV is essential.
23
24        1. Close all open file descriptors except standard input, output, and
25           error (i.e. the first three file descriptors 0, 1, 2). This ensures
26           that no accidentally passed file descriptor stays around in the
27           daemon process. On Linux, this is best implemented by iterating
28           through /proc/self/fd, with a fallback of iterating from file
29           descriptor 3 to the value returned by getrlimit() for
30           RLIMIT_NOFILE.
31
32        2. Reset all signal handlers to their default. This is best done by
33           iterating through the available signals up to the limit of _NSIG
34           and resetting them to SIG_DFL.
35
36        3. Reset the signal mask using sigprocmask().
37
38        4. Sanitize the environment block, removing or resetting environment
39           variables that might negatively impact daemon runtime.
40
41        5. Call fork(), to create a background process.
42
43        6. In the child, call setsid() to detach from any terminal and create
44           an independent session.
45
46        7. In the child, call fork() again, to ensure that the daemon can
47           never re-acquire a terminal again. (This relevant if the program —
48           and all its dependencies — does not carefully specify `O_NOCTTY` on
49           each and every single `open()` call that might potentially open a
50           TTY device node.)
51
52        8. Call exit() in the first child, so that only the second child (the
53           actual daemon process) stays around. This ensures that the daemon
54           process is re-parented to init/PID 1, as all daemons should be.
55
56        9. In the daemon process, connect /dev/null to standard input, output,
57           and error.
58
59       10. In the daemon process, reset the umask to 0, so that the file modes
60           passed to open(), mkdir() and suchlike directly control the access
61           mode of the created files and directories.
62
63       11. In the daemon process, change the current directory to the root
64           directory (/), in order to avoid that the daemon involuntarily
65           blocks mount points from being unmounted.
66
67       12. In the daemon process, write the daemon PID (as returned by
68           getpid()) to a PID file, for example /run/foobar.pid (for a
69           hypothetical daemon "foobar") to ensure that the daemon cannot be
70           started more than once. This must be implemented in race-free
71           fashion so that the PID file is only updated when it is verified at
72           the same time that the PID previously stored in the PID file no
73           longer exists or belongs to a foreign process.
74
75       13. In the daemon process, drop privileges, if possible and applicable.
76
77       14. From the daemon process, notify the original process started that
78           initialization is complete. This can be implemented via an unnamed
79           pipe or similar communication channel that is created before the
80           first fork() and hence available in both the original and the
81           daemon process.
82
83       15. Call exit() in the original process. The process that invoked the
84           daemon must be able to rely on that this exit() happens after
85           initialization is complete and all external communication channels
86           are established and accessible.
87
88       The BSD daemon() function should not be used, as it implements only a
89       subset of these steps.
90
91       A daemon that needs to provide compatibility with SysV systems should
92       implement the scheme pointed out above. However, it is recommended to
93       make this behavior optional and configurable via a command line
94       argument to ease debugging as well as to simplify integration into
95       systems using systemd.
96
97   New-Style Daemons
98       Modern services for Linux should be implemented as new-style daemons.
99       This makes it easier to supervise and control them at runtime and
100       simplifies their implementation.
101
102       For developing a new-style daemon, none of the initialization steps
103       recommended for SysV daemons need to be implemented. New-style init
104       systems such as systemd make all of them redundant. Moreover, since
105       some of these steps interfere with process monitoring, file descriptor
106       passing and other functionality of the init system, it is recommended
107       not to execute them when run as new-style service.
108
109       Note that new-style init systems guarantee execution of daemon
110       processes in a clean process context: it is guaranteed that the
111       environment block is sanitized, that the signal handlers and mask is
112       reset and that no left-over file descriptors are passed. Daemons will
113       be executed in their own session, with standard input connected to
114       /dev/null and standard output/error connected to the systemd-
115       journald.service(8) logging service, unless otherwise configured. The
116       umask is reset.
117
118       It is recommended for new-style daemons to implement the following:
119
120        1. If SIGTERM is received, shut down the daemon and exit cleanly.
121
122        2. If SIGHUP is received, reload the configuration files, if this
123           applies.
124
125        3. Provide a correct exit code from the main daemon process, as this
126           is used by the init system to detect service errors and problems.
127           It is recommended to follow the exit code scheme as defined in the
128           LSB recommendations for SysV init scripts[1].
129
130        4. If possible and applicable, expose the daemon's control interface
131           via the D-Bus IPC system and grab a bus name as last step of
132           initialization.
133
134        5. For integration in systemd, provide a .service unit file that
135           carries information about starting, stopping and otherwise
136           maintaining the daemon. See systemd.service(5) for details.
137
138        6. As much as possible, rely on the init system's functionality to
139           limit the access of the daemon to files, services and other
140           resources, i.e. in the case of systemd, rely on systemd's resource
141           limit control instead of implementing your own, rely on systemd's
142           privilege dropping code instead of implementing it in the daemon,
143           and similar. See systemd.exec(5) for the available controls.
144
145        7. If D-Bus is used, make your daemon bus-activatable by supplying a
146           D-Bus service activation configuration file. This has multiple
147           advantages: your daemon may be started lazily on-demand; it may be
148           started in parallel to other daemons requiring it — which maximizes
149           parallelization and boot-up speed; your daemon can be restarted on
150           failure without losing any bus requests, as the bus queues requests
151           for activatable services. See below for details.
152
153        8. If your daemon provides services to other local processes or remote
154           clients via a socket, it should be made socket-activatable
155           following the scheme pointed out below. Like D-Bus activation, this
156           enables on-demand starting of services as well as it allows
157           improved parallelization of service start-up. Also, for state-less
158           protocols (such as syslog, DNS), a daemon implementing socket-based
159           activation can be restarted without losing a single request. See
160           below for details.
161
162        9. If applicable, a daemon should notify the init system about startup
163           completion or status updates via the sd_notify(3) interface.
164
165       10. Instead of using the syslog() call to log directly to the system
166           syslog service, a new-style daemon may choose to simply log to
167           standard error via fprintf(), which is then forwarded to syslog by
168           the init system. If log levels are necessary, these can be encoded
169           by prefixing individual log lines with strings like "<4>" (for log
170           level 4 "WARNING" in the syslog priority scheme), following a
171           similar style as the Linux kernel's printk() level system. For
172           details, see sd-daemon(3) and systemd.exec(5).
173
174       11. As new-style daemons are invoked without a controlling TTY (but as
175           their own session leaders) care should be taken to always specify
176           `O_NOCTTY` on `open()` calls that possibly reference a TTY device
177           node, so that no controlling TTY is accidentally acquired.
178
179       These recommendations are similar but not identical to the Apple MacOS
180       X Daemon Requirements[2].
181

ACTIVATION

183       New-style init systems provide multiple additional mechanisms to
184       activate services, as detailed below. It is common that services are
185       configured to be activated via more than one mechanism at the same
186       time. An example for systemd: bluetoothd.service might get activated
187       either when Bluetooth hardware is plugged in, or when an application
188       accesses its programming interfaces via D-Bus. Or, a print server
189       daemon might get activated when traffic arrives at an IPP port, or when
190       a printer is plugged in, or when a file is queued in the printer spool
191       directory. Even for services that are intended to be started on system
192       bootup unconditionally, it is a good idea to implement some of the
193       various activation schemes outlined below, in order to maximize
194       parallelization. If a daemon implements a D-Bus service or listening
195       socket, implementing the full bus and socket activation scheme allows
196       starting of the daemon with its clients in parallel (which speeds up
197       boot-up), since all its communication channels are established already,
198       and no request is lost because client requests will be queued by the
199       bus system (in case of D-Bus) or the kernel (in case of sockets) until
200       the activation is completed.
201
202   Activation on Boot
203       Old-style daemons are usually activated exclusively on boot (and
204       manually by the administrator) via SysV init scripts, as detailed in
205       the LSB Linux Standard Base Core Specification[1]. This method of
206       activation is supported ubiquitously on Linux init systems, both
207       old-style and new-style systems. Among other issues, SysV init scripts
208       have the disadvantage of involving shell scripts in the boot process.
209       New-style init systems generally employ updated versions of activation,
210       both during boot-up and during runtime and using more minimal service
211       description files.
212
213       In systemd, if the developer or administrator wants to make sure that a
214       service or other unit is activated automatically on boot, it is
215       recommended to place a symlink to the unit file in the .wants/
216       directory of either multi-user.target or graphical.target, which are
217       normally used as boot targets at system startup. See systemd.unit(5)
218       for details about the .wants/ directories, and systemd.special(7) for
219       details about the two boot targets.
220
221   Socket-Based Activation
222       In order to maximize the possible parallelization and robustness and
223       simplify configuration and development, it is recommended for all
224       new-style daemons that communicate via listening sockets to employ
225       socket-based activation. In a socket-based activation scheme, the
226       creation and binding of the listening socket as primary communication
227       channel of daemons to local (and sometimes remote) clients is moved out
228       of the daemon code and into the init system. Based on per-daemon
229       configuration, the init system installs the sockets and then hands them
230       off to the spawned process as soon as the respective daemon is to be
231       started. Optionally, activation of the service can be delayed until the
232       first inbound traffic arrives at the socket to implement on-demand
233       activation of daemons. However, the primary advantage of this scheme is
234       that all providers and all consumers of the sockets can be started in
235       parallel as soon as all sockets are established. In addition to that,
236       daemons can be restarted with losing only a minimal number of client
237       transactions, or even any client request at all (the latter is
238       particularly true for state-less protocols, such as DNS or syslog),
239       because the socket stays bound and accessible during the restart, and
240       all requests are queued while the daemon cannot process them.
241
242       New-style daemons which support socket activation must be able to
243       receive their sockets from the init system instead of creating and
244       binding them themselves. For details about the programming interfaces
245       for this scheme provided by systemd, see sd_listen_fds(3) and sd-
246       daemon(3). For details about porting existing daemons to socket-based
247       activation, see below. With minimal effort, it is possible to implement
248       socket-based activation in addition to traditional internal socket
249       creation in the same codebase in order to support both new-style and
250       old-style init systems from the same daemon binary.
251
252       systemd implements socket-based activation via .socket units, which are
253       described in systemd.socket(5). When configuring socket units for
254       socket-based activation, it is essential that all listening sockets are
255       pulled in by the special target unit sockets.target. It is recommended
256       to place a WantedBy=sockets.target directive in the "[Install]" section
257       to automatically add such a dependency on installation of a socket
258       unit. Unless DefaultDependencies=no is set, the necessary ordering
259       dependencies are implicitly created for all socket units. For more
260       information about sockets.target, see systemd.special(7). It is not
261       necessary or recommended to place any additional dependencies on socket
262       units (for example from multi-user.target or suchlike) when one is
263       installed in sockets.target.
264
265   Bus-Based Activation
266       When the D-Bus IPC system is used for communication with clients,
267       new-style daemons should employ bus activation so that they are
268       automatically activated when a client application accesses their IPC
269       interfaces. This is configured in D-Bus service files (not to be
270       confused with systemd service unit files!). To ensure that D-Bus uses
271       systemd to start-up and maintain the daemon, use the SystemdService=
272       directive in these service files to configure the matching systemd
273       service for a D-Bus service. e.g.: For a D-Bus service whose D-Bus
274       activation file is named org.freedesktop.RealtimeKit.service, make sure
275       to set SystemdService=rtkit-daemon.service in that file to bind it to
276       the systemd service rtkit-daemon.service. This is needed to make sure
277       that the daemon is started in a race-free fashion when activated via
278       multiple mechanisms simultaneously.
279
280   Device-Based Activation
281       Often, daemons that manage a particular type of hardware should be
282       activated only when the hardware of the respective kind is plugged in
283       or otherwise becomes available. In a new-style init system, it is
284       possible to bind activation to hardware plug/unplug events. In systemd,
285       kernel devices appearing in the sysfs/udev device tree can be exposed
286       as units if they are tagged with the string "systemd". Like any other
287       kind of unit, they may then pull in other units when activated (i.e.
288       plugged in) and thus implement device-based activation. systemd
289       dependencies may be encoded in the udev database via the SYSTEMD_WANTS=
290       property. See systemd.device(5) for details. Often, it is nicer to pull
291       in services from devices only indirectly via dedicated targets.
292       Example: Instead of pulling in bluetoothd.service from all the various
293       bluetooth dongles and other hardware available, pull in
294       bluetooth.target from them and bluetoothd.service from that target.
295       This provides for nicer abstraction and gives administrators the option
296       to enable bluetoothd.service via controlling a bluetooth.target.wants/
297       symlink uniformly with a command like enable of systemctl(1) instead of
298       manipulating the udev ruleset.
299
300   Path-Based Activation
301       Often, runtime of daemons processing spool files or directories (such
302       as a printing system) can be delayed until these file system objects
303       change state, or become non-empty. New-style init systems provide a way
304       to bind service activation to file system changes. systemd implements
305       this scheme via path-based activation configured in .path units, as
306       outlined in systemd.path(5).
307
308   Timer-Based Activation
309       Some daemons that implement clean-up jobs that are intended to be
310       executed in regular intervals benefit from timer-based activation. In
311       systemd, this is implemented via .timer units, as described in
312       systemd.timer(5).
313
314   Other Forms of Activation
315       Other forms of activation have been suggested and implemented in some
316       systems. However, there are often simpler or better alternatives, or
317       they can be put together of combinations of the schemes above. Example:
318       Sometimes, it appears useful to start daemons or .socket units when a
319       specific IP address is configured on a network interface, because
320       network sockets shall be bound to the address. However, an alternative
321       to implement this is by utilizing the Linux IP_FREEBIND socket option,
322       as accessible via FreeBind=yes in systemd socket files (see
323       systemd.socket(5) for details). This option, when enabled, allows
324       sockets to be bound to a non-local, not configured IP address, and
325       hence allows bindings to a particular IP address before it actually
326       becomes available, making such an explicit dependency to the configured
327       address redundant. Another often suggested trigger for service
328       activation is low system load. However, here too, a more convincing
329       approach might be to make proper use of features of the operating
330       system, in particular, the CPU or I/O scheduler of Linux. Instead of
331       scheduling jobs from userspace based on monitoring the OS scheduler, it
332       is advisable to leave the scheduling of processes to the OS scheduler
333       itself. systemd provides fine-grained access to the CPU and I/O
334       schedulers. If a process executed by the init system shall not
335       negatively impact the amount of CPU or I/O bandwidth available to other
336       processes, it should be configured with CPUSchedulingPolicy=idle and/or
337       IOSchedulingClass=idle. Optionally, this may be combined with
338       timer-based activation to schedule background jobs during runtime and
339       with minimal impact on the system, and remove it from the boot phase
340       itself.
341

INTEGRATION WITH SYSTEMD

343   Writing systemd Unit Files
344       When writing systemd unit files, it is recommended to consider the
345       following suggestions:
346
347        1. If possible, do not use the Type=forking setting in service files.
348           But if you do, make sure to set the PID file path using PIDFile=.
349           See systemd.service(5) for details.
350
351        2. If your daemon registers a D-Bus name on the bus, make sure to use
352           Type=dbus in the service file if possible.
353
354        3. Make sure to set a good human-readable description string with
355           Description=.
356
357        4. Do not disable DefaultDependencies=, unless you really know what
358           you do and your unit is involved in early boot or late system
359           shutdown.
360
361        5. Normally, little if any dependencies should need to be defined
362           explicitly. However, if you do configure explicit dependencies,
363           only refer to unit names listed on systemd.special(7) or names
364           introduced by your own package to keep the unit file operating
365           system-independent.
366
367        6. Make sure to include an "[Install]" section including installation
368           information for the unit file. See systemd.unit(5) for details. To
369           activate your service on boot, make sure to add a
370           WantedBy=multi-user.target or WantedBy=graphical.target directive.
371           To activate your socket on boot, make sure to add
372           WantedBy=sockets.target. Usually, you also want to make sure that
373           when your service is installed, your socket is installed too, hence
374           add Also=foo.socket in your service file foo.service, for a
375           hypothetical program foo.
376
377   Installing systemd Service Files
378       At the build installation time (e.g.  make install during package
379       build), packages are recommended to install their systemd unit files in
380       the directory returned by pkg-config systemd
381       --variable=systemdsystemunitdir (for system services) or pkg-config
382       systemd --variable=systemduserunitdir (for user services). This will
383       make the services available in the system on explicit request but not
384       activate them automatically during boot. Optionally, during package
385       installation (e.g.  rpm -i by the administrator), symlinks should be
386       created in the systemd configuration directories via the enable command
387       of the systemctl(1) tool to activate them automatically on boot.
388
389       Packages using autoconf(1) are recommended to use a configure script
390       excerpt like the following to determine the unit installation path
391       during source configuration:
392
393           PKG_PROG_PKG_CONFIG
394           AC_ARG_WITH([systemdsystemunitdir],
395                [AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files])],,
396                [with_systemdsystemunitdir=auto])
397           AS_IF([test "x$with_systemdsystemunitdir" = "xyes" -o "x$with_systemdsystemunitdir" = "xauto"], [
398                def_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)
399
400                AS_IF([test "x$def_systemdsystemunitdir" = "x"],
401              [AS_IF([test "x$with_systemdsystemunitdir" = "xyes"],
402               [AC_MSG_ERROR([systemd support requested but pkg-config unable to query systemd package])])
403               with_systemdsystemunitdir=no],
404              [with_systemdsystemunitdir="$def_systemdsystemunitdir"])])
405           AS_IF([test "x$with_systemdsystemunitdir" != "xno"],
406                 [AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])])
407           AM_CONDITIONAL([HAVE_SYSTEMD], [test "x$with_systemdsystemunitdir" != "xno"])
408
409       This snippet allows automatic installation of the unit files on systemd
410       machines, and optionally allows their installation even on machines
411       lacking systemd. (Modification of this snippet for the user unit
412       directory is left as an exercise for the reader.)
413
414       Additionally, to ensure that make distcheck continues to work, it is
415       recommended to add the following to the top-level Makefile.am file in
416       automake(1)-based projects:
417
418           AM_DISTCHECK_CONFIGURE_FLAGS = \
419             --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)
420
421       Finally, unit files should be installed in the system with an automake
422       excerpt like the following:
423
424           if HAVE_SYSTEMD
425           systemdsystemunit_DATA = \
426             foobar.socket \
427             foobar.service
428           endif
429
430       In the rpm(8) .spec file, use snippets like the following to
431       enable/disable the service during installation/deinstallation. This
432       makes use of the RPM macros shipped along systemd. Consult the
433       packaging guidelines of your distribution for details and the
434       equivalent for other package managers.
435
436       At the top of the file:
437
438           BuildRequires: systemd
439           %{?systemd_requires}
440
441       And as scriptlets, further down:
442
443           %post
444           %systemd_post foobar.service foobar.socket
445
446           %preun
447           %systemd_preun foobar.service foobar.socket
448
449           %postun
450           %systemd_postun
451
452       If the service shall be restarted during upgrades, replace the
453       "%postun" scriptlet above with the following:
454
455           %postun
456           %systemd_postun_with_restart foobar.service
457
458       Note that "%systemd_post" and "%systemd_preun" expect the names of all
459       units that are installed/removed as arguments, separated by spaces.
460       "%systemd_postun" expects no arguments.  "%systemd_postun_with_restart"
461       expects the units to restart as arguments.
462
463       To facilitate upgrades from a package version that shipped only SysV
464       init scripts to a package version that ships both a SysV init script
465       and a native systemd service file, use a fragment like the following:
466
467           %triggerun -- foobar < 0.47.11-1
468           if /sbin/chkconfig --level 5 foobar ; then
469             /bin/systemctl --no-reload enable foobar.service foobar.socket >/dev/null 2>&1 || :
470           fi
471
472       Where 0.47.11-1 is the first package version that includes the native
473       unit file. This fragment will ensure that the first time the unit file
474       is installed, it will be enabled if and only if the SysV init script is
475       enabled, thus making sure that the enable status is not changed. Note
476       that chkconfig is a command specific to Fedora which can be used to
477       check whether a SysV init script is enabled. Other operating systems
478       will have to use different commands here.
479

PORTING EXISTING DAEMONS

481       Since new-style init systems such as systemd are compatible with
482       traditional SysV init systems, it is not strictly necessary to port
483       existing daemons to the new style. However, doing so offers additional
484       functionality to the daemons as well as simplifying integration into
485       new-style init systems.
486
487       To port an existing SysV compatible daemon, the following steps are
488       recommended:
489
490        1. If not already implemented, add an optional command line switch to
491           the daemon to disable daemonization. This is useful not only for
492           using the daemon in new-style init systems, but also to ease
493           debugging.
494
495        2. If the daemon offers interfaces to other software running on the
496           local system via local AF_UNIX sockets, consider implementing
497           socket-based activation (see above). Usually, a minimal patch is
498           sufficient to implement this: Extend the socket creation in the
499           daemon code so that sd_listen_fds(3) is checked for already passed
500           sockets first. If sockets are passed (i.e. when sd_listen_fds()
501           returns a positive value), skip the socket creation step and use
502           the passed sockets. Secondly, ensure that the file system socket
503           nodes for local AF_UNIX sockets used in the socket-based activation
504           are not removed when the daemon shuts down, if sockets have been
505           passed. Third, if the daemon normally closes all remaining open
506           file descriptors as part of its initialization, the sockets passed
507           from the init system must be spared. Since new-style init systems
508           guarantee that no left-over file descriptors are passed to executed
509           processes, it might be a good choice to simply skip the closing of
510           all remaining open file descriptors if sockets are passed.
511
512        3. Write and install a systemd unit file for the service (and the
513           sockets if socket-based activation is used, as well as a path unit
514           file, if the daemon processes a spool directory), see above for
515           details.
516
517        4. If the daemon exposes interfaces via D-Bus, write and install a
518           D-Bus activation file for the service, see above for details.
519

PLACING DAEMON DATA

521       It is recommended to follow the general guidelines for placing package
522       files, as discussed in file-hierarchy(7).
523

SEE ALSO

525       systemd(1), sd-daemon(3), sd_listen_fds(3), sd_notify(3), daemon(3),
526       systemd.service(5), file-hierarchy(7)
527

NOTES

529        1. LSB recommendations for SysV init scripts
530           http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
531
532        2. Apple MacOS X Daemon Requirements
533           https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
534
535
536
537systemd 241                                                          DAEMON(7)
Impressum