1DAEMON(7)                           daemon                           DAEMON(7)


6       daemon - Writing and packaging system daemons


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.
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.
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.
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.
36        3. Reset the signal mask using sigprocmask().
38        4. Sanitize the environment block, removing or resetting environment
39           variables that might negatively impact daemon runtime.
41        5. Call fork(), to create a background process.
43        6. In the child, call setsid() to detach from any terminal and create
44           an independent session.
46        7. In the child, call fork() again, to ensure that the daemon can
47           never re-acquire a terminal again.
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.
53        9. In the daemon process, connect /dev/null to standard input, output,
54           and error.
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.
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.
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.
72       13. In the daemon process, drop privileges, if possible and applicable.
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.
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.
85       The BSD daemon() function should not be used, as it implements only a
86       subset of these steps.
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.
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.
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.
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 connected to
111       /dev/null and standard output/error connected to the systemd-
112       journald.service(8) logging service, unless otherwise configured. The
113       umask is reset.
115       It is recommended for new-style daemons to implement the following:
117        1. If SIGTERM is received, shut down the daemon and exit cleanly.
119        2. If SIGHUP is received, reload the configuration files, if this
120           applies.
122        3. Provide a correct exit code from the main daemon process, as this
123           is used by the init system to detect service errors and problems.
124           It is recommended to follow the exit code scheme as defined in the
125           LSB recommendations for SysV init scripts[1].
127        4. If possible and applicable, expose the daemon's control interface
128           via the D-Bus IPC system and grab a bus name as last step of
129           initialization.
131        5. For integration in systemd, provide a .service unit file that
132           carries information about starting, stopping and otherwise
133           maintaining the daemon. See systemd.service(5) for details.
135        6. As much as possible, rely on the init system's functionality to
136           limit the access of the daemon to files, services and other
137           resources, i.e. in the case of systemd, rely on systemd's resource
138           limit control instead of implementing your own, rely on systemd's
139           privilege dropping code instead of implementing it in the daemon,
140           and similar. See systemd.exec(5) for the available controls.
142        7. If D-Bus is used, make your daemon bus-activatable by supplying a
143           D-Bus service activation configuration file. This has multiple
144           advantages: your daemon may be started lazily on-demand; it may be
145           started in parallel to other daemons requiring it — which maximizes
146           parallelization and boot-up speed; your daemon can be restarted on
147           failure without losing any bus requests, as the bus queues requests
148           for activatable services. See below for details.
150        8. If your daemon provides services to other local processes or remote
151           clients via a socket, it should be made socket-activatable
152           following the scheme pointed out below. Like D-Bus activation, this
153           enables on-demand starting of services as well as it allows
154           improved parallelization of service start-up. Also, for state-less
155           protocols (such as syslog, DNS), a daemon implementing socket-based
156           activation can be restarted without losing a single request. See
157           below for details.
159        9. If applicable, a daemon should notify the init system about startup
160           completion or status updates via the sd_notify(3) interface.
162       10. Instead of using the syslog() call to log directly to the system
163           syslog service, a new-style daemon may choose to simply log to
164           standard error via fprintf(), which is then forwarded to syslog by
165           the init system. If log levels are necessary, these can be encoded
166           by prefixing individual log lines with strings like "<4>" (for log
167           level 4 "WARNING" in the syslog priority scheme), following a
168           similar style as the Linux kernel's printk() level system. For
169           details, see sd-daemon(3) and systemd.exec(5).
171       These recommendations are similar but not identical to the Apple MacOS
172       X Daemon Requirements[2].


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


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


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


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


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


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