1 <?xml version='1.0'?> <!--*-nxml-*-->
2 <!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
6 This file is part of systemd.
8 Copyright 2010 Lennart Poettering
10 systemd is free software; you can redistribute it and/or modify it
11 under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 systemd is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 <refentry id="daemon">
28 <productname>systemd</productname>
32 <contrib>Developer</contrib>
33 <firstname>Lennart</firstname>
34 <surname>Poettering</surname>
35 <email>lennart@poettering.net</email>
41 <refentrytitle>daemon</refentrytitle>
42 <manvolnum>7</manvolnum>
46 <refname>daemon</refname>
47 <refpurpose>Writing and Packaging System Daemons</refpurpose>
51 <title>Description</title>
53 <para>A daemon is a service process that runs in the
54 background and supervises the system or provides
55 functionality to other processes. Traditionally,
56 daemons are implemented following a scheme originating
57 in SysV Unix. Modern daemons should follow a simpler
58 yet more powerful scheme (here called "new-style"
59 daemons), as implemented by
60 <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>. </para>
63 <title>SysV Daemons</title>
65 <para>When a traditional SysV daemon
66 starts, it should execute the following steps
67 as part of the initialization. Note that these
68 steps are unnecessary for new-style daemons (see below),
69 and should only be implemented if compatibility
70 with SysV is essential.</para>
73 <listitem><para>Close all open file
74 descriptors except STDIN, STDOUT,
75 STDERR (i.e. the first three file
76 descriptors 0, 1, 2). This ensures
77 that no accidentally passed file
78 descriptor stays around in the daemon
79 process. On Linux this is best
80 implemented by iterating through
81 <filename>/proc/self/fd</filename>,
82 with a fallback of iterating from file
83 descriptor 3 to the value returned by
84 <function>getrlimit()</function> for
85 RLIMIT_NOFILE.</para></listitem>
87 <listitem><para>Reset all signal
88 handlers to their default. This is
89 best done by iterating through the
90 available signals up to the limit of
91 _NSIG and resetting them to
92 SIG_DFL.</para></listitem>
94 <listitem><para>Reset the signal mask
96 <function>sigprocmask()</function>.</para></listitem>
98 <listitem><para>Sanitize the
99 environment block, removing or
100 resetting environment variables that
101 might negatively impact daemon
102 runtime.</para></listitem>
104 <listitem><para>Call <function>fork()</function>,
105 to create a background
106 process.</para></listitem>
108 <listitem><para>In the child, call
109 <function>setsid()</function> to
110 detach from any terminal and create an
111 independent session.</para></listitem>
113 <listitem><para>In the child, call
114 <function>fork()</function> again, to
115 ensure the daemon can never re-aquire
116 a terminal again.</para></listitem>
118 <listitem><para>Call <function>exit()</function> in the
119 first child, so that only the second
120 child (the actual daemon process)
121 stays around. This ensures that the
122 daemon process is reparented to
123 init/PID 1, as all daemons should
124 be.</para></listitem>
126 <listitem><para>In the daemon process,
127 connect <filename>/dev/null</filename>
129 STDERR.</para></listitem>
131 <listitem><para>In the daemon process,
132 reset the umask to 0, so that the file
133 modes passed to <function>open()</function>, <function>mkdir()</function> and
134 suchlike directly control the access
135 mode of the created files and
136 directories.</para></listitem>
138 <listitem><para>In the daemon process,
139 change the current directory to the
140 root directory (/), in order to avoid
141 that the daemon involuntarily
142 blocks mount points from being
143 unmounted.</para></listitem>
145 <listitem><para>In the daemon process,
146 write the daemon PID (as returned by
147 <function>getpid()</function>) to a
148 PID file, for example
149 <filename>/var/run/foobar.pid</filename>
150 (for a hypothetical daemon "foobar"),
151 to ensure that the daemon cannot be
152 started more than once. This must be
153 implemented in race-free fashion so
154 that the PID file is only updated when
155 at the same time it is verified that
156 the PID previously stored in the PID
157 file no longer exists or belongs to a
158 foreign process. Commonly some kind of
159 file locking is employed to implement
160 this logic.</para></listitem>
162 <listitem><para>In the daemon process,
163 drop privileges, if possible and
164 applicable.</para></listitem>
166 <listitem><para>From the daemon
167 process notify the original process
168 started that initialization is
169 complete. This can be implemented via
170 an unnamed pipe or similar
171 communication channel that is created
173 <function>fork()</function> and hence
174 available in both the original and the
175 daemon process.</para></listitem>
178 <function>exit()</function> in the
179 original process. The process that
180 invoked the daemon must be able to
182 <function>exit()</function> happens
183 after initialization is complete and
184 all external communication channels
186 accessible.</para></listitem>
189 <para>The BSD <function>daemon()</function> function should not be
190 used, as it implements only a subset of these steps.</para>
192 <para>A daemon that needs to provide
193 compatibility with SysV systems should
194 implement the scheme pointed out
195 above. However, it is recommended to make this
196 behaviour optional and configurable via a
197 command line argument, to ease debugging as
198 well as to simplify integration into systems
199 using systemd.</para>
203 <title>New-Style Daemons</title>
205 <para>Modern services for Linux should be
206 implemented as new-style daemons. This makes it
207 easier to supervise and control them at
208 runtime and simplifies their
209 implementation.</para>
211 <para>For developing a new-style daemon none
212 of the initialization steps recommended for
213 SysV daemons need to be implemented. New-style
214 init systems such as systemd make all of them
215 redundant. Moreover, since some of these steps
216 interfere with process monitoring, file
217 descriptor passing and other functionality of
218 the init system it is recommended not to
219 execute them when run as new-style
222 <para>Note that new-style init systems
223 guarantee execution of daemon processes in
224 clean process contexts: it is guaranteed that
225 the environment block is sanitized, that the
226 signal handlers and mask is reset and that no
227 left-over file descriptors are passed. Daemons
228 will be executed in their own session, and
229 STDIN/STDOUT/STDERR connected to
230 <filename>/dev/null</filename> unless
231 otherwise configured. The umask is reset.</para>
233 <para>It is recommended for new-style daemons
234 to implement the following:</para>
237 <listitem><para>If SIGTERM is
238 received, shut down the daemon and
239 exit cleanly.</para></listitem>
241 <listitem><para>If SIGHUP is received,
242 reload the configuration files, if
243 this applies.</para></listitem>
245 <listitem><para>Provide a correct exit
246 code from the main daemon process, as
247 this is used by the init system to
248 detect service errors and problems. It
249 is recommended to follow the exit code
250 scheme as defined in the <ulink
251 url="http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html">LSB
252 recommendations for SysV init
253 scripts</ulink>.</para></listitem>
255 <listitem><para>As much as possible,
256 rely on systemd's functionality to
257 limit the access of the daemon to
258 files, services and other
259 resources. i.e. rely on systemd's
260 resource limit control instead of
261 implementing your own, rely on
262 systemd's privilege dropping code
263 instead of implementing it in the
264 daemon, and similar. See
265 <citerefentry><refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum></citerefentry>
267 controls.</para></listitem>
269 <listitem><para>If possible and
270 applicable expose the daemon's control
271 interface via the D-Bus IPC system and
272 grab a bus name as last step of
273 initialization.</para></listitem>
275 <listitem><para>If D-Bus is used, make
276 your daemon bus-activatable, via
277 supplying a D-Bus service activation
278 configuration file. This has multiple
279 advantages: your daemon may be started
280 lazily on-demand; it may be started in
281 parallel to other daemons requiring it
282 -- which maximizes parallelization and
283 boot-up speed; your daemon can be
284 restarted on failure, without losing
285 any bus requests, as the bus queues
286 requests for activatable services. See
287 below for details.</para></listitem>
289 <listitem><para>If your daemon
290 provides services to other local
291 processes or remote clients via a
292 socket, it should be made
293 socket-activatable following the
294 scheme pointed out below. Like D-Bus
295 activation this enables on-demand
296 starting of services as well as it
297 allows improved parallelization of
298 service start-up. Also, for state-less
299 protocols (such as syslog, DNS) a
300 daemon implementing socket-based
301 activation can be restarted without
302 losing a single request. See below for
303 details.</para></listitem>
305 <listitem><para>If applicable a daemon
306 should notify the init system about
307 startup completion or status updates
309 <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>
310 interface.</para></listitem>
312 <listitem><para>Instead of using the
313 <function>syslog()</function> call to log directly to the
314 system logger, a new-style daemon may
315 choose to simply log to STDERR via
316 <function>fprintf()</function>, which is then forwarded to
317 syslog by the init system. If log
318 priorities are necessary these can be
319 encoded by prefixing individual log
320 lines with strings like "<4>"
321 (for log priority 4 "WARNING" in the
322 syslog priority scheme), following a
323 similar style as the Linux kernel's
324 <function>printk()</function> priority system. In fact,
325 using this style of logging also
326 enables the init system to optionally
327 direct all application logging to the
328 kernel log buffer (kmsg), as
330 <citerefentry><refentrytitle>dmesg</refentrytitle><manvolnum>1</manvolnum></citerefentry>. This
331 kind of logging may be enabled by
333 <varname>StandardError=syslog</varname>
334 in the service unit file. For details
336 <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>7</manvolnum></citerefentry>
338 <citerefentry><refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para></listitem>
342 <para>These recommendations are similar but
343 not identical to the <ulink
344 url="http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/LaunchOnDemandDaemons.html#//apple_ref/doc/uid/TP40001762-104738">Apple
345 MacOS X Daemon Requirements</ulink>.</para>
349 <title>Socket-Based Activation</title>
353 <title>Bus-Based Activation</title>
357 <title>Path-Based Activation</title>
361 <title>Writing Systemd Unit Files</title>
363 <para>When writing systemd unit files, it is
364 recommended to consider the following
368 <listitem><para>If possible do not use
369 the <varname>Type=forking</varname>
370 setting in service files. But if you
371 do, make sure to set the PID file path
372 using <varname>PIDFile=</varname>. See
373 <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>
374 for details.</para></listitem>
376 <listitem><para>If your daemon
377 registers a D-Bus name on the bus,
379 <varname>Type=dbus</varname> if
380 possible.</para></listitem>
382 <listitem><para>Make sure to set a
383 good human-readable description string
385 <varname>Description=</varname>.</para></listitem>
387 <listitem><para>Do not disable
388 <varname>DefaultDependencies=</varname>,
389 unless you really know what you do and
390 your unit is involved in early boot or
391 late system shutdown.</para></listitem>
393 <listitem><para>Normally, little if
394 any dependencies should need to
395 be defined explicitly. However, if you
396 do configure explicit dependencies, only refer to
398 <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>7</manvolnum></citerefentry>
399 or names introduced by your own
400 package to keep the unit file
402 system-independent.</para></listitem>
404 <listitem><para>Make sure to include
405 an <literal>[Install]</literal> section including
406 installation information for the unit
408 <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>
409 for details. To activate your service
410 on boot make sure to add a
411 <varname>WantedBy=multi-user.target</varname>
413 <varname>WantedBy=graphical.target</varname> directive.</para></listitem>
419 <title>Installing Service Files</title>
421 <para>At the build installation time
422 (e.g. <command>make install</command> during
423 package build) packages are recommended to
424 install their systemd unit files in the
425 directory returned by <command>pkg-config
427 --variable=systemdsystemnunitdir</command>
428 (for system services),
429 resp. <command>pkg-config systemd
430 --variable=systemdsessionunitdir</command>
431 (for session services). This will make the
432 services available in the system on explicit
433 request but not activate them automatically
434 during boot. Optionally, during package
435 installation (e.g. <command>rpm -i</command>
436 by the administrator) symlinks should be
437 created in the systemd configuration
439 <citerefentry><refentrytitle>systemd-install</refentrytitle><manvolnum>1</manvolnum></citerefentry>
440 tool, to activate them automatically on
444 <citerefentry><refentrytitle>autoconf</refentrytitle><manvolnum>1</manvolnum></citerefentry>
445 are recommended to use a configure script
446 excerpt like the following to determine the
447 unit installation path during source
448 configuration:</para>
450 <programlisting>PKG_PROG_PKG_CONFIG
451 AC_ARG_WITH([systemdsystemunitdir],
452 AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files]),
453 [], [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)])
454 AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])
455 AM_CONDITIONAL(HAVE_SYSTEMD, [test -n "$with_systemdsystemunitdir"])</programlisting>
457 <para>This snippet allows automatic
458 installation of the unit files on systemd
459 machines, and optionally allows their
460 installation even on machines lacking
461 systemd. (Modification of this snippet for the
462 session unit directory is left as excercise to the
465 <para>Additionally, to ensure that
466 <command>make distcheck</command> continues to
467 work, it is recommended to add the following
468 to the top-level <filename>Makefile.am</filename>
470 <citerefentry><refentrytitle>automake</refentrytitle><manvolnum>1</manvolnum></citerefentry>-based
473 <programlisting>DISTCHECK_CONFIGURE_FLAGS = \
474 --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)</programlisting>
476 <para>Finally, unit files should be installed in the system with an automake excerpt like the following:</para>
478 <programlisting>if HAVE_SYSTEMD
479 systemdsystemunit_DATA = \
482 endif</programlisting>
485 <citerefentry><refentrytitle>rpm</refentrytitle><manvolnum>8</manvolnum></citerefentry>
486 <filename>.spec</filename> file use a snippet like
487 the following to enable/disable the service
488 during installation/deinstallation. Consult
489 the packaging guidelines of your distribution
490 for details and the equivalent for other
491 packaging managers:</para>
493 <programlisting>%post
494 /usr/bin/systemd-install enable foobar.service foobar.socket >/dev/null 2>&1 || :
497 if [ "$1" -eq 0 ]; then
498 /usr/bin/systemd-install disable foobar.service foobar.socket >/dev/null 2>&1 || :
504 <title>Porting Existing Daemons</title>
506 <para>Since new-style init systems such as
507 systemd are compatible with traditional SysV
508 init systems it is not strictly necessary to
509 port existing daemons to the new
510 style. However doing this offers additional
511 functionality to the daemons as well as it
512 simplifies integration into new-style init
515 <para>To port an existing SysV compatible
516 daemon the following steps are
520 <listitem><para>If not already
521 implemented, add an optional command
522 line switch to the daemon to disable
523 daemonization. This is useful not only
524 for using the daemon in new-style init
525 systems, but also to ease debugging.</para></listitem>
527 <listitem><para>If the daemon offers
528 interfaces to other software running
529 on the local system via local AF_UNIX
530 sockets, consider implementing
531 socket-based activation (see
532 above). Usually a minimal patch is
533 sufficient to implement this: Extend
534 the socket creation in the daemon code
536 <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>
537 is checked for already passed sockets
538 first. If sockets are passed
540 <function>sd_listen_fds()</function>
541 returns a positive value), skip the
542 socket createn step and use the passed
543 sockets. Secondly, ensure that the
544 file-system socket nodes for local
545 AF_UNIX sockets used in the
546 socket-based activation are not
547 removed when the daemon shuts down, if
548 sockets have been passed. Third, if
549 the daemon normally closes all
550 remaining open file descriptors as
551 part of its initialization, the
552 sockets passed from the init system
553 must be spared. Since new-style init
554 systems guarantee that no left-over
555 file descriptors are passed to
556 executed processes, it might be a good
557 choice to simply skip the closing of
558 all remaining open file descriptors if
560 passed.</para></listitem>
562 <listitem><para>Write and install a
563 systemd unit file for the service (and
564 the sockets if socket-based activation
565 is used, as well as a path unit file,
566 if the daemon processes a spool
567 directory), see above for
568 details.</para></listitem>
570 <listitem><para>If the daemon exposes
571 interfaces via D-Bus, write and
572 install a D-Bus activation file for
573 the service, see above for
574 details.</para></listitem>
583 <title>See Also</title>
585 <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
586 <citerefentry><refentrytitle>systemd-install</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
587 <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>7</manvolnum></citerefentry>,
588 <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
589 <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
590 <citerefentry><refentrytitle>daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>