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.
48
49        8. Call exit() in the first child, so that only the second child (the
50           actual daemon process) stays around. This ensures that the daemon
51           process is re-parented to init/PID 1, as all daemons should be.
52
53        9. In the daemon process, connect /dev/null to standard input, output,
54           and error.
55
56       10. In the daemon process, reset the umask to 0, so that the file modes
57           passed to open(), mkdir() and suchlike directly control the access
58           mode of the created files and directories.
59
60       11. In the daemon process, change the current directory to the root
61           directory (/), in order to avoid that the daemon involuntarily
62           blocks mount points from being unmounted.
63
64       12. In the daemon process, write the daemon PID (as returned by
65           getpid()) to a PID file, for example /run/foobar.pid (for a
66           hypothetical daemon "foobar") to ensure that the daemon cannot be
67           started more than once. This must be implemented in race-free
68           fashion so that the PID file is only updated when it is verified at
69           the same time that the PID previously stored in the PID file no
70           longer exists or belongs to a foreign process.
71
72       13. In the daemon process, drop privileges, if possible and applicable.
73
74       14. From the daemon process, notify the original process started that
75           initialization is complete. This can be implemented via an unnamed
76           pipe or similar communication channel that is created before the
77           first fork() and hence available in both the original and the
78           daemon process.
79
80       15. Call exit() in the original process. The process that invoked the
81           daemon must be able to rely on that this exit() happens after
82           initialization is complete and all external communication channels
83           are established and accessible.
84
85       The BSD daemon() function should not be used, as it implements only a
86       subset of these steps.
87
88       A daemon that needs to provide compatibility with SysV systems should
89       implement the scheme pointed out above. However, it is recommended to
90       make this behavior optional and configurable via a command line
91       argument to ease debugging as well as to simplify integration into
92       systems using systemd.
93
94   New-Style Daemons
95       Modern services for Linux should be implemented as new-style daemons.
96       This makes it easier to supervise and control them at runtime and
97       simplifies their implementation.
98
99       For developing a new-style daemon, none of the initialization steps
100       recommended for SysV daemons need to be implemented. New-style init
101       systems such as systemd make all of them redundant. Moreover, since
102       some of these steps interfere with process monitoring, file descriptor
103       passing and other functionality of the init system, it is recommended
104       not to execute them when run as new-style service.
105
106       Note that new-style init systems guarantee execution of daemon
107       processes in a clean process context: it is guaranteed that the
108       environment block is sanitized, that the signal handlers and mask is
109       reset and that no left-over file descriptors are passed. Daemons will
110       be executed in their own session, with standard input/output/error
111       connected to /dev/null unless otherwise configured. The umask is reset.
112
113       It is recommended for new-style daemons to implement the following:
114
115        1. If SIGTERM is received, shut down the daemon and exit cleanly.
116
117        2. If SIGHUP is received, reload the configuration files, if this
118           applies.
119
120        3. Provide a correct exit code from the main daemon process, as this
121           is used by the init system to detect service errors and problems.
122           It is recommended to follow the exit code scheme as defined in the
123           LSB recommendations for SysV init scripts[1].
124
125        4. If possible and applicable, expose the daemon's control interface
126           via the D-Bus IPC system and grab a bus name as last step of
127           initialization.
128
129        5. For integration in systemd, provide a .service unit file that
130           carries information about starting, stopping and otherwise
131           maintaining the daemon. See systemd.service(5) for details.
132
133        6. As much as possible, rely on the init system's functionality to
134           limit the access of the daemon to files, services and other
135           resources, i.e. in the case of systemd, rely on systemd's resource
136           limit control instead of implementing your own, rely on systemd's
137           privilege dropping code instead of implementing it in the daemon,
138           and similar. See systemd.exec(5) for the available controls.
139
140        7. If D-Bus is used, make your daemon bus-activatable by supplying a
141           D-Bus service activation configuration file. This has multiple
142           advantages: your daemon may be started lazily on-demand; it may be
143           started in parallel to other daemons requiring it -- which
144           maximizes parallelization and boot-up speed; your daemon can be
145           restarted on failure without losing any bus requests, as the bus
146           queues requests for activatable services. See below for details.
147
148        8. If your daemon provides services to other local processes or remote
149           clients via a socket, it should be made socket-activatable
150           following the scheme pointed out below. Like D-Bus activation, this
151           enables on-demand starting of services as well as it allows
152           improved parallelization of service start-up. Also, for state-less
153           protocols (such as syslog, DNS), a daemon implementing socket-based
154           activation can be restarted without losing a single request. See
155           below for details.
156
157        9. If applicable, a daemon should notify the init system about startup
158           completion or status updates via the sd_notify(3) interface.
159
160       10. Instead of using the syslog() call to log directly to the system
161           syslog service, a new-style daemon may choose to simply log to
162           standard error via fprintf(), which is then forwarded to syslog by
163           the init system. If log levels are necessary, these can be encoded
164           by prefixing individual log lines with strings like "<4>" (for log
165           level 4 "WARNING" in the syslog priority scheme), following a
166           similar style as the Linux kernel's printk() level system. For
167           details, see sd-daemon(3) and systemd.exec(5).
168
169       These recommendations are similar but not identical to the Apple MacOS
170       X Daemon Requirements[2].
171

ACTIVATION

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

INTEGRATION WITH SYSTEMD

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

PORTING EXISTING DAEMONS

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

PLACING DAEMON DATA

511       It is recommended to follow the general guidelines for placing package
512       files, as discussed in file-hierarchy(7).
513

SEE ALSO

515       systemd(1), sd-daemon(3), sd_listen_fds(3), sd_notify(3), daemon(3),
516       systemd.service(5), file-hierarchy(7)
517

NOTES

519        1. LSB recommendations for SysV init scripts
520           http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
521
522        2. Apple MacOS X Daemon Requirements
523           https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
524
525
526
527systemd 219                                                          DAEMON(7)
Impressum