1DAEMON(7) daemon DAEMON(7)
2
3
4
6 daemon - Writing and Packaging System Daemons
7
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 STDIN, STDOUT, STDERR (i.e.
25 the first three file descriptors 0, 1, 2). This ensures that no
26 accidentally passed file descriptor stays around in the daemon
27 process. On Linux this is best implemented by iterating through
28 /proc/self/fd, with a fallback of iterating from file descriptor 3
29 to the value returned by getrlimit() for RLIMIT_NOFILE.
30
31 2. Reset all signal handlers to their default. This is best done by
32 iterating through the available signals up to the limit of _NSIG
33 and resetting them to SIG_DFL.
34
35 3. Reset the signal mask using sigprocmask().
36
37 4. Sanitize the environment block, removing or resetting environment
38 variables that might negatively impact daemon runtime.
39
40 5. Call fork(), to create a background process.
41
42 6. In the child, call setsid() to detach from any terminal and create
43 an independent session.
44
45 7. In the child, call fork() again, to ensure the daemon can never
46 re-aquire a terminal again.
47
48 8. Call exit() in the first child, so that only the second child (the
49 actual daemon process) stays around. This ensures that the daemon
50 process is reparented to init/PID 1, as all daemons should be.
51
52 9. In the daemon process, connect /dev/null to STDIN, STDOUT, STDERR.
53
54 10. In the daemon process, reset the umask to 0, so that the file modes
55 passed to open(), mkdir() and suchlike directly control the access
56 mode of the created files and directories.
57
58 11. In the daemon process, change the current directory to the root
59 directory (/), in order to avoid that the daemon involuntarily
60 blocks mount points from being unmounted.
61
62 12. In the daemon process, write the daemon PID (as returned by
63 getpid()) to a PID file, for example /var/run/foobar.pid (for a
64 hypothetical daemon "foobar"), to ensure that the daemon cannot be
65 started more than once. This must be implemented in race-free
66 fashion so that the PID file is only updated when at the same time
67 it is verified that the PID previously stored in the PID file no
68 longer exists or belongs to a foreign process. Commonly some kind
69 of file locking is employed to implement this logic.
70
71 13. In the daemon process, drop privileges, if possible and applicable.
72
73 14. From the daemon process notify the original process started that
74 initialization is complete. This can be implemented via an unnamed
75 pipe or similar communication channel that is created before the
76 first fork() and hence available in both the original and the
77 daemon process.
78
79 15. Call exit() in the original process. The process that invoked the
80 daemon must be able to rely that this exit() happens after
81 initialization is complete and all external communication channels
82 established and accessible.
83
84 The BSD daemon() function should not be used, as it implements only a
85 subset of these steps.
86
87 A daemon that needs to provide compatibility with SysV systems should
88 implement the scheme pointed out above. However, it is recommended to
89 make this behaviour optional and configurable via a command line
90 argument, to ease debugging as well as to simplify integration into
91 systems using systemd.
92
93 New-Style Daemons
94 Modern services for Linux should be implemented as new-style daemons.
95 This makes it easier to supervise and control them at runtime and
96 simplifies their implementation.
97
98 For developing a new-style daemon none of the initialization steps
99 recommended for SysV daemons need to be implemented. New-style init
100 systems such as systemd make all of them redundant. Moreover, since
101 some of these steps interfere with process monitoring, file descriptor
102 passing and other functionality of the init system it is recommended
103 not to execute them when run as new-style service.
104
105 Note that new-style init systems guarantee execution of daemon
106 processes in clean process contexts: it is guaranteed that the
107 environment block is sanitized, that the signal handlers and mask is
108 reset and that no left-over file descriptors are passed. Daemons will
109 be executed in their own session, and STDIN/STDOUT/STDERR connected to
110 /dev/null unless otherwise configured. The umask is reset.
111
112 It is recommended for new-style daemons to implement the following:
113
114 1. If SIGTERM is received, shut down the daemon and exit cleanly.
115
116 2. If SIGHUP is received, reload the configuration files, if this
117 applies.
118
119 3. Provide a correct exit code from the main daemon process, as this
120 is used by the init system to detect service errors and problems.
121 It is recommended to follow the exit code scheme as defined in the
122 LSB recommendations for SysV init scripts[1].
123
124 4. If possible and applicable expose the daemon´s control interface
125 via the D-Bus IPC system and grab a bus name as last step of
126 initialization.
127
128 5. For integration in systemd, provide a .service unit file that
129 carries information about starting, stopping and otherwise
130 maintaining the daemon. See systemd.service(5) for details.
131
132 6. As much as possible, rely on the init systemd´s functionality to
133 limit the access of the daemon to files, services and other
134 resources. i.e. in the case of systemd, rely on systemd´s resource
135 limit control instead of implementing your own, rely on systemd´s
136 privilege dropping code instead of implementing it in the daemon,
137 and similar. See systemd.exec(5) for the available controls.
138
139 7. If D-Bus is used, make your daemon bus-activatable, via supplying a
140 D-Bus service activation configuration file. This has multiple
141 advantages: your daemon may be started lazily on-demand; it may be
142 started in parallel to other daemons requiring it -- which
143 maximizes parallelization and boot-up speed; your daemon can be
144 restarted on failure, without losing any bus requests, as the bus
145 queues requests for activatable services. See below for details.
146
147 8. If your daemon provides services to other local processes or remote
148 clients via a socket, it should be made socket-activatable
149 following the scheme pointed out below. Like D-Bus activation this
150 enables on-demand starting of services as well as it allows
151 improved parallelization of service start-up. Also, for state-less
152 protocols (such as syslog, DNS) a daemon implementing socket-based
153 activation can be restarted without losing a single request. See
154 below for details.
155
156 9. If applicable a daemon should notify the init system about startup
157 completion or status updates via the sd_notify(3) interface.
158
159 10. Instead of using the syslog() call to log directly to the system
160 logger, a new-style daemon may choose to simply log to STDERR via
161 fprintf(), which is then forwarded to syslog by the init system. If
162 log priorities are necessary these can be encoded by prefixing
163 individual log lines with strings like "<4>" (for log priority 4
164 "WARNING" in the syslog priority scheme), following a similar style
165 as the Linux kernel´s printk() priority system. In fact, using this
166 style of logging also enables the init system to optionally direct
167 all application logging to the kernel log buffer (kmsg), as
168 accessible via dmesg(1). This kind of logging may be enabled by
169 setting StandardError=syslog in the service unit file. For details
170 see sd-daemon(7) and systemd.exec(5).
171
172 These recommendations are similar but not identical to the Apple MacOS
173 X Daemon Requirements[2].
174
176 New-style init systems provide multiple additional mechanisms to
177 activate services, as detailed below. It is common that services are
178 configured to be activated via more than one mechanism at the same
179 time. An example for systemd: bluetoothd.service might get activated
180 either when Bluetooth hardware is plugged in, or when an application
181 accesses its programming interfaces via D-Bus. Or, a print server
182 daemon might get activated when traffic arrives at an IPP port, or when
183 a printer is plugged in, or when a file is queued in the printer spool
184 directory. Even for services that are intended to be started on system
185 bootup unconditionally it is a good idea to implement some of the
186 various activation schemes outlined below, in order to maximize
187 parallelization: if a daemon implements a D-Bus service or listening
188 socket, implementing the full bus and socket activation scheme allows
189 starting of the daemon with its clients in parallel (which speeds up
190 boot-up), since all its communication channels are established already,
191 and no request is lost because client requests will be queued by the
192 bus system (in case of D-Bus) or the kernel (in case of sockets), until
193 the activation is completed.
194
195 Activation on Boot
196 Old-style daemons are usually activated exclusively on boot (and
197 manually by the administrator) via SysV init scripts, as detailed in
198 the LSB Linux Standard Base Core Specification[1]. This method of
199 activation is supported ubiquitiously on Linux init systems, both
200 old-style and new-style systems. Among other issues SysV init scripts
201 have the disadvantage of involving shell scripts in the boot process.
202 New-style init systems generally employ updated versions of activation,
203 both during boot-up and during runtime and using more minimal service
204 description files.
205
206 In systemd, if the developer or administrator wants to make sure a
207 service or other unit is activated automatically on boot it is
208 recommended to place a symlink to the unit file in the .wants/
209 directory of either multi-user.target or graphical.target, which are
210 normally used as boot targets at system startup. See systemd.unit(5)
211 for details about the .wants/ directories, and systemd.special(7) for
212 details about the two boot targets.
213
214 Socket-Based Activation
215 In order to maximize the possible parallelization and robustness and
216 simplify configuration and development, it is recommended for all
217 new-style daemons that communicate via listening sockets to employ
218 socket-based activation. In a socket-based activation scheme the
219 creation and binding of the listening socket as primary communication
220 channel of daemons to local (and sometimes remote) clients is moved out
221 of the daemon code and into the init system. Based on per-daemon
222 configuration the init system installs the sockets and then hands them
223 off to the spawned process as soon as the respective daemon is to be
224 started. Optionally activation of the service can be delayed until the
225 first inbound traffic arrives at the socket, to implement on-demand
226 activation of daemons. However, the primary advantage of this scheme is
227 that all providers and all consumers of the sockets can be started in
228 parallel as soon as all sockets are established. In addition to that
229 daemons can be restarted with losing only a minimal number of client
230 transactions or even any client request at all (the latter is
231 particularly true for state-less protocols, such as DNS or syslog),
232 because the socket stays bound and accessible during the restart, and
233 all requests are queued while the daemon cannot process them.
234
235 New-style daemons which support socket activation must be able to
236 receive their sockets from the init system, instead of of creating and
237 binding them themselves. For details about the programming interfaces
238 for this scheme provided by systemd see sd_listen_fds(3) and sd-
239 daemon(7). For details about porting existing daemons to socket-based
240 activation see below. With minimal effort it is possible to implement
241 socket-based activation in addition to traditional internal socket
242 creation in the same codebase in order to support both new-style and
243 old-style init systems from the same daemon binary.
244
245 systemd implements socket-based activation via .socket units, which are
246 described in systemd.socket(5). When configuring socket units for
247 socket-based activation it is essential that all listening sockets are
248 pulled in by the special target unit sockets.target. It is recommended
249 to place a WantedBy=sockets.target directive in the [Install] section,
250 to automatically add such a dependency on installation of a socket
251 unit. Unless DefaultDependencies=no is set the necessary ordering
252 dependencies are implicitly created for all socket units. For more
253 information about sockets.target see systemd.special(7). It is not
254 necessary or recommended to place any additional dependencies on socket
255 units (for example from multi-user.target or suchlike) when one is
256 installed in sockets.target.
257
258 Bus-Based Activation
259 When the D-Bus IPC system is used for communication with clients,
260 new-style daemons should employ bus activation so that they are
261 automatically activated when a client application accesses their IPC
262 interfaces. This is configured in D-Bus service files (not to be
263 confused with systemd service unit files!). To ensure that D-Bus uses
264 systemd to start-up and maintain the daemon use the SystemdService=
265 directive in these service files, to configure the matching systemd
266 service for a D-Bus service. e.g.: for a D-Bus service whose D-Bus
267 activation file is named org.freedesktop.RealtimeKit.service, make sure
268 to set SystemdService=rtkit-daemon.service in that file, to bind it to
269 the systemd service rtkit-daemon.service. This is needed to make sure
270 that the daemon is started in a race-free fashion when activated via
271 multiple mechanisms simultaneously.
272
273 Device-Based Activation
274 Often, daemons that manage a particular type of hardware should be
275 activated only when the hardware of the respective kind is plugged in
276 or otherwise becomes available. In a new-style init system it is
277 possible to bind activation to hardware plug/unplug events. In systemd,
278 kernel devices appearing in the sysfs/udev device tree can be exposed
279 as units if they are tagged with the string "systemd". Like any other
280 kind of unit they may then pull in other units when activated (i.e.
281 Plugged in) and thus implement device-based activation. Systemd
282 dependencies may be encoded in the udev database via the SYSTEMD_WANTS=
283 property. See systemd.device(5) for details. Often it is nicer to pull
284 in services from devices only indirectly via dedicated targets.
285 Example: instead of pulling in bluetoothd.service from all the various
286 bluetooth dongles and other hardware available, pull in
287 bluetooth.target from them and bluetoothd.service from that target.
288 This provides for nicer abstraction and gives administrators the option
289 to enable bluetoothd.service via controlling a bluetooth.target.wants/
290 symlink uniformly with a command like enable of systemctl(1) instead of
291 manipulating the udev ruleset.
292
293 Path-Based Activation
294 Often, runtime of daemons processing spool files or directories (such
295 as a printing system) can be delayed until these file system objects
296 change state, or become non-empty. New-style init systems provide a way
297 to bind service activation to file system changes. systemd implements
298 this scheme via path-based activation configured in .path units, as
299 outlined in systemd.path(5).
300
301 Timer-Based Activation
302 Some daemons that implement clean-up jobs that are intended to be
303 executed in regular intervals benefit from timer-based activation. In
304 systemd, this is implemented via .timer units, as described in
305 systemd.timer(5).
306
307 Other Forms of Activation
308 Other forms of activation have been suggested and implemented in some
309 systems. However, often there are simpler or better alternatives, or
310 they can be put together of combinations of the schemes above. Example:
311 sometimes it appears useful to start daemons or .socket units when a
312 specific IP address is configured on a network interface, because
313 network sockets shall be bound to the address. However, an alternative
314 to implement this is by utilizing the Linux IP_FREEBIND socket option,
315 as accessible via FreeBind=yes in systemd socket files (see
316 systemd.socket(5) for details). This option, when enabled, allows
317 sockets to be bound to a non-local, not configured IP address, and
318 hence allows bindings to a particular IP address before it actually
319 becomes available, making such an explicit dependency to the configured
320 address redundant. Another often suggested trigger for service
321 activation is low system load. However, here too, a more convincing
322 approach might be to make proper use of features of the operating
323 system: in particular, the CPU or IO scheduler of Linux. Instead of
324 scheduling jobs from userspace based on monitoring the OS scheduler, it
325 is advisable to leave the scheduling of processes to the OS scheduler
326 itself. systemd provides fine-grained access to the CPU and IO
327 schedulers. If a process executed by the init system shall not
328 negatively impact the amount of CPU or IO bandwith available to other
329 processes, it should be configured with CPUSchedulingPolicy=idle and/or
330 IOSchedulingClass=idle. Optionally, this may be combined with
331 timer-based activation to schedule background jobs during runtime and
332 with minimal impact on the system, and remove it from the boot phase
333 itself.
334
336 Writing Systemd Unit Files
337 When writing systemd unit files, it is recommended to consider the
338 following suggestions:
339
340 1. If possible do not use the Type=forking setting in service files.
341 But if you do, make sure to set the PID file path using PIDFile=.
342 See systemd.service(5) for details.
343
344 2. If your daemon registers a D-Bus name on the bus, make sure to use
345 Type=dbus in the service file if possible.
346
347 3. Make sure to set a good human-readable description string with
348 Description=.
349
350 4. Do not disable DefaultDependencies=, unless you really know what
351 you do and your unit is involved in early boot or late system
352 shutdown.
353
354 5. Normally, little if any dependencies should need to be defined
355 explicitly. However, if you do configure explicit dependencies,
356 only refer to unit names listed on systemd.special(7) or names
357 introduced by your own package to keep the unit file operating
358 system-independent.
359
360 6. Since not all syslog implementations are socket-activatable yet, it
361 is recommended to place an After=syslog.target dependency in
362 service files for daemons that can log to syslog. syslog.target
363 then either pulls in the syslog daemon itself or simply the
364 activation socket. A Wants= or even Requires= dependency should
365 generally not be added, since it should be up to the administrator
366 whether he wants to enable logging or not, and most syslog clients
367 work fine if no log daemon is running.
368
369 7. Make sure to include an [Install] section including installation
370 information for the unit file. See systemd.unit(5) for details. To
371 activate your service on boot make sure to add a
372 WantedBy=multi-user.target or WantedBy=graphical.target directive.
373 To activate your socket on boot, make sure to add
374 WantedBy=sockets.target. Usually you also want to make sure that
375 when your service is installed your socket is installed too, hence
376 add Also=foo.socket in your service file foo.service, for a
377 hypothetical program foo.
378
379 Installing Systemd Service Files
380 At the build installation time (e.g. make install during package
381 build) packages are recommended to install their systemd unit files in
382 the directory returned by pkg-config systemd
383 --variable=systemdsystemunitdir (for system services), resp.
384 pkg-config systemd --variable=systemdsessionunitdir (for session
385 services). This will make the services available in the system on
386 explicit request but not activate them automatically during boot.
387 Optionally, during package installation (e.g. rpm -i by the
388 administrator) symlinks should be created in the systemd configuration
389 directories via the enable command of the systemctl(1) tool, to
390 activate them automatically on boot.
391
392 Packages using autoconf(1) are recommended to use a configure script
393 excerpt like the following to determine the unit installation path
394 during source configuration:
395
396 PKG_PROG_PKG_CONFIG
397 AC_ARG_WITH([systemdsystemunitdir],
398 AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files]),
399 [], [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)])
400 AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])
401 AM_CONDITIONAL(HAVE_SYSTEMD, [test -n "$with_systemdsystemunitdir"])
402
403 This snippet allows automatic installation of the unit files on systemd
404 machines, and optionally allows their installation even on machines
405 lacking systemd. (Modification of this snippet for the session unit
406 directory is left as excercise to the reader.)
407
408 Additionally, to ensure that make distcheck continues to work, it is
409 recommended to add the following to the top-level Makefile.am file in
410 automake(1)-based projects:
411
412 DISTCHECK_CONFIGURE_FLAGS = \
413 --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)
414
415 Finally, unit files should be installed in the system with an automake
416 excerpt like the following:
417
418 if HAVE_SYSTEMD
419 systemdsystemunit_DATA = \
420 foobar.socket \
421 foobar.service
422 endif
423
424 In the rpm(8) .spec file use a snippet like the following to
425 enable/disable the service during installation/deinstallation. Consult
426 the packaging guidelines of your distribution for details and the
427 equivalent for other package managers:
428
429 %post
430 if [ $1 -eq 1 ]; then
431 # On install, enable (but don´t start) the units by default
432 /bin/systemctl enable foobar.service foobar.socket >/dev/null 2>&1 || :
433
434 # Alternatively, just call /bin/systemctl daemon-reload here,
435 # if the daemon should not be enabled by default on package
436 # installation
437 fi
438
439 %preun
440 if [ $1 -eq 0 ]; then
441 # On uninstall, disable and stop the units
442 /bin/systemctl disable foobar.service foobar.socket >/dev/null 2>&1 || :
443 /bin/systemctl stop foobar.service foobar.socket >/dev/null 2>&1 || :
444 fi
445
446 %postun
447 # On upgrade and uninstall, reload init system configuration, to make systemd honour changed unit files
448 /bin/systemctl daemon-reload >/dev/null 2>&1 || :
449 if [ $1 -ge 1 ] ; then
450 # Optionally, on upgrade, restart the daemon
451 /bin/systemctl try-restart foobar.service >/dev/null 2>&1 || :
452 fi
453
454 Depending on whether your service should or should not be
455 started/stopped/restarted during package installation, deinstallation
456 or upgrade, a different set of commands may be specified. See
457 systemctl(1) for details.
458
459 To facilitate upgrades from a package version that shipped only SysV
460 init scripts to a package version that ships both a SysV init script
461 and a native systemd service file, use a fragment like the following:
462
463 %triggerun -- foobar < 0.47.11-1
464 if /sbin/chkconfig foobar ; then
465 /bin/systemctl enable foobar.service foobar.socket >/dev/null 2>&1 || :
466 fi
467
468 Where 0.47.11-1 is the first package version that includes the native
469 unit file. This fragment will ensure that the first time the unit file
470 is installed it will be enabled if and only if the SysV init script is
471 enabled, thus making sure that the enable status is not changed. Note
472 that chkconfig is a command specific to Fedora which can be used to
473 check whether a SysV init script is enabled. Other operating systems
474 will have to use different commands here.
475
477 Since new-style init systems such as systemd are compatible with
478 traditional SysV init systems it is not strictly necessary to port
479 existing daemons to the new style. However doing so offers additional
480 functionality to the daemons as well as simplifying integration into
481 new-style init systems.
482
483 To port an existing SysV compatible daemon the following steps are
484 recommended:
485
486 1. If not already implemented, add an optional command line switch to
487 the daemon to disable daemonization. This is useful not only for
488 using the daemon in new-style init systems, but also to ease
489 debugging.
490
491 2. If the daemon offers interfaces to other software running on the
492 local system via local AF_UNIX sockets, consider implementing
493 socket-based activation (see above). Usually a minimal patch is
494 sufficient to implement this: Extend the socket creation in the
495 daemon code so that sd_listen_fds(3) is checked for already passed
496 sockets first. If sockets are passed (i.e. when sd_listen_fds()
497 returns a positive value), skip the socket creation step and use
498 the passed sockets. Secondly, ensure that the file-system socket
499 nodes for local AF_UNIX sockets used in the socket-based activation
500 are not removed when the daemon shuts down, if sockets have been
501 passed. Third, if the daemon normally closes all remaining open
502 file descriptors as part of its initialization, the sockets passed
503 from the init system must be spared. Since new-style init systems
504 guarantee that no left-over file descriptors are passed to executed
505 processes, it might be a good choice to simply skip the closing of
506 all remaining open file descriptors if sockets are passed.
507
508 3. Write and install a systemd unit file for the service (and the
509 sockets if socket-based activation is used, as well as a path unit
510 file, if the daemon processes a spool directory), see above for
511 details.
512
513 4. If the daemon exposes interfaces via D-Bus, write and install a
514 D-Bus activation file for the service, see above for details.
515
517 systemd(1), sd-daemon(7), sd_listen_fds(3), sd_notify(3), daemon(3),
518 systemd.service(5)
519
521 Lennart Poettering <lennart@poettering.net>
522 Developer
523
525 1. LSB recommendations for SysV init scripts
526 http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
527
528 2. Apple MacOS X Daemon Requirements
529 http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/LaunchOnDemandDaemons.html#//apple_ref/doc/uid/TP40001762-104738
530
531
532
533systemd 09/14/2010 DAEMON(7)