1<?xml version='1.0'?> <!--*-nxml-*-->
2<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
3  "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
4<!-- SPDX-License-Identifier: LGPL-2.1-or-later -->
5
6<refentry id="daemon">
7
8  <refentryinfo>
9    <title>daemon</title>
10    <productname>systemd</productname>
11  </refentryinfo>
12
13  <refmeta>
14    <refentrytitle>daemon</refentrytitle>
15    <manvolnum>7</manvolnum>
16  </refmeta>
17
18  <refnamediv>
19    <refname>daemon</refname>
20    <refpurpose>Writing and packaging system daemons</refpurpose>
21  </refnamediv>
22
23  <refsect1>
24    <title>Description</title>
25
26    <para>A daemon is a service process that runs in the background
27    and supervises the system or provides functionality to other
28    processes. Traditionally, daemons are implemented following a
29    scheme originating in SysV Unix. Modern daemons should follow a
30    simpler yet more powerful scheme (here called "new-style"
31    daemons), as implemented by
32    <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>.
33    This manual page covers both schemes, and in particular includes
34    recommendations for daemons that shall be included in the systemd
35    init system.</para>
36
37    <refsect2>
38      <title>SysV Daemons</title>
39
40      <para>When a traditional SysV daemon starts, it should execute
41      the following steps as part of the initialization. Note that
42      these steps are unnecessary for new-style daemons (see below),
43      and should only be implemented if compatibility with SysV is
44      essential.</para>
45
46      <orderedlist>
47        <listitem><para>Close all open file descriptors except
48        standard input, output, and error (i.e. the first three file
49        descriptors 0, 1, 2). This ensures that no accidentally passed
50        file descriptor stays around in the daemon process. On Linux,
51        this is best implemented by iterating through
52        <filename>/proc/self/fd</filename>, with a fallback of
53        iterating from file descriptor 3 to the value returned by
54        <function>getrlimit()</function> for
55        <constant>RLIMIT_NOFILE</constant>. </para></listitem>
56
57        <listitem><para>Reset all signal handlers to their default.
58        This is best done by iterating through the available signals
59        up to the limit of <constant>_NSIG</constant> and resetting
60        them to <constant>SIG_DFL</constant>.</para></listitem>
61
62        <listitem><para>Reset the signal mask
63        using
64        <function>sigprocmask()</function>.</para></listitem>
65
66        <listitem><para>Sanitize the environment block, removing or
67        resetting environment variables that might negatively impact
68        daemon runtime.</para></listitem>
69
70        <listitem><para>Call <function>fork()</function>, to create a
71        background process.</para></listitem>
72
73        <listitem><para>In the child, call
74        <function>setsid()</function> to detach from any terminal and
75        create an independent session.</para></listitem>
76
77        <listitem><para>In the child, call <function>fork()</function> again, to ensure that the daemon can
78        never re-acquire a terminal again. (This relevant if the program — and all its dependencies — does
79        not carefully specify `O_NOCTTY` on each and every single `open()` call that might potentially open a
80        TTY device node.)</para></listitem>
81
82        <listitem><para>Call <function>exit()</function> in the first
83        child, so that only the second child (the actual daemon
84        process) stays around. This ensures that the daemon process is
85        re-parented to init/PID 1, as all daemons should
86        be.</para></listitem>
87
88        <listitem><para>In the daemon process, connect
89        <filename>/dev/null</filename> to standard input, output, and
90        error.</para></listitem>
91
92        <listitem><para>In the daemon process, reset the umask to 0,
93        so that the file modes passed to <function>open()</function>,
94        <function>mkdir()</function> and suchlike directly control the
95        access mode of the created files and
96        directories.</para></listitem>
97
98        <listitem><para>In the daemon process, change the current
99        directory to the root directory (/), in order to avoid that
100        the daemon involuntarily blocks mount points from being
101        unmounted.</para></listitem>
102
103        <listitem><para>In the daemon process, write the daemon PID
104        (as returned by <function>getpid()</function>) to a PID file,
105        for example <filename index='false'>/run/foobar.pid</filename> (for a
106        hypothetical daemon "foobar") to ensure that the daemon cannot
107        be started more than once. This must be implemented in
108        race-free fashion so that the PID file is only updated when it
109        is verified at the same time that the PID previously stored in
110        the PID file no longer exists or belongs to a foreign
111        process.</para></listitem>
112
113        <listitem><para>In the daemon process, drop privileges, if
114        possible and applicable.</para></listitem>
115
116        <listitem><para>From the daemon process, notify the original
117        process started that initialization is complete. This can be
118        implemented via an unnamed pipe or similar communication
119        channel that is created before the first
120        <function>fork()</function> and hence available in both the
121        original and the daemon process.</para></listitem>
122
123        <listitem><para>Call <function>exit()</function> in the
124        original process. The process that invoked the daemon must be
125        able to rely on that this <function>exit()</function> happens
126        after initialization is complete and all external
127        communication channels are established and
128        accessible.</para></listitem>
129      </orderedlist>
130
131      <para>The BSD <function>daemon()</function> function should not
132      be used, as it implements only a subset of these steps.</para>
133
134      <para>A daemon that needs to provide compatibility with SysV
135      systems should implement the scheme pointed out above. However,
136      it is recommended to make this behavior optional and
137      configurable via a command line argument to ease debugging as
138      well as to simplify integration into systems using
139      systemd.</para>
140    </refsect2>
141
142    <refsect2>
143      <title>New-Style Daemons</title>
144
145      <para>Modern services for Linux should be implemented as
146      new-style daemons. This makes it easier to supervise and control
147      them at runtime and simplifies their implementation.</para>
148
149      <para>For developing a new-style daemon, none of the
150      initialization steps recommended for SysV daemons need to be
151      implemented. New-style init systems such as systemd make all of
152      them redundant. Moreover, since some of these steps interfere
153      with process monitoring, file descriptor passing and other
154      functionality of the init system, it is recommended not to
155      execute them when run as new-style service.</para>
156
157      <para>Note that new-style init systems guarantee execution of daemon processes in a clean process context: it is
158      guaranteed that the environment block is sanitized, that the signal handlers and mask is reset and that no
159      left-over file descriptors are passed. Daemons will be executed in their own session, with standard input
160      connected to <filename>/dev/null</filename> and standard output/error connected to the
161      <citerefentry><refentrytitle>systemd-journald.service</refentrytitle><manvolnum>8</manvolnum></citerefentry>
162      logging service, unless otherwise configured. The umask is reset.
163      </para>
164
165      <para>It is recommended for new-style daemons to implement the
166      following:</para>
167
168      <orderedlist>
169        <listitem><para>If <constant>SIGTERM</constant> is received,
170        shut down the daemon and exit cleanly.</para></listitem>
171
172        <listitem><para>If <constant>SIGHUP</constant> is received,
173        reload the configuration files, if this
174        applies.</para></listitem>
175
176        <listitem><para>Provide a correct exit code from the main
177        daemon process, as this is used by the init system to detect
178        service errors and problems. It is recommended to follow the
179        exit code scheme as defined in the <ulink
180        url="http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html">LSB
181        recommendations for SysV init
182        scripts</ulink>.</para></listitem>
183
184        <listitem><para>If possible and applicable, expose the
185        daemon's control interface via the D-Bus IPC system and grab a
186        bus name as last step of initialization.</para></listitem>
187
188        <listitem><para>For integration in systemd, provide a
189        <filename>.service</filename> unit file that carries
190        information about starting, stopping and otherwise maintaining
191        the daemon. See
192        <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>
193        for details.</para></listitem>
194
195        <listitem><para>As much as possible, rely on the init system's
196        functionality to limit the access of the daemon to files,
197        services and other resources, i.e. in the case of systemd,
198        rely on systemd's resource limit control instead of
199        implementing your own, rely on systemd's privilege dropping
200        code instead of implementing it in the daemon, and similar.
201        See
202        <citerefentry><refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum></citerefentry>
203        for the available controls.</para></listitem>
204
205        <listitem><para>If D-Bus is used, make your daemon
206        bus-activatable by supplying a D-Bus service activation
207        configuration file. This has multiple advantages: your daemon
208        may be started lazily on-demand; it may be started in parallel
209        to other daemons requiring it — which maximizes
210        parallelization and boot-up speed; your daemon can be
211        restarted on failure without losing any bus requests, as the
212        bus queues requests for activatable services. See below for
213        details.</para></listitem>
214
215        <listitem><para>If your daemon provides services to other
216        local processes or remote clients via a socket, it should be
217        made socket-activatable following the scheme pointed out
218        below. Like D-Bus activation, this enables on-demand starting
219        of services as well as it allows improved parallelization of
220        service start-up. Also, for state-less protocols (such as
221        syslog, DNS), a daemon implementing socket-based activation
222        can be restarted without losing a single request. See below
223        for details.</para></listitem>
224
225        <listitem><para>If applicable, a daemon should notify the init
226        system about startup completion or status updates via the
227        <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>
228        interface.</para></listitem>
229
230        <listitem><para>Instead of using the
231        <function>syslog()</function> call to log directly to the
232        system syslog service, a new-style daemon may choose to simply
233        log to standard error via <function>fprintf()</function>,
234        which is then forwarded to syslog by the init system. If log
235        levels are necessary, these can be encoded by prefixing
236        individual log lines with strings like
237        <literal>&lt;4&gt;</literal> (for log level 4 "WARNING" in the
238        syslog priority scheme), following a similar style as the
239        Linux kernel's <function>printk()</function> level system. For
240        details, see
241        <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>
242        and
243        <citerefentry><refentrytitle>systemd.exec</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para></listitem>
244
245        <listitem><para>As new-style daemons are invoked without a controlling TTY (but as their own session
246        leaders) care should be taken to always specify `O_NOCTTY` on `open()` calls that possibly reference
247        a TTY device node, so that no controlling TTY is accidentally acquired.</para></listitem>
248
249      </orderedlist>
250
251      <para>These recommendations are similar but not identical to the
252      <ulink
253      url="https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html">Apple
254      MacOS X Daemon Requirements</ulink>.</para>
255    </refsect2>
256
257  </refsect1>
258  <refsect1>
259    <title>Activation</title>
260
261    <para>New-style init systems provide multiple additional
262    mechanisms to activate services, as detailed below. It is common
263    that services are configured to be activated via more than one
264    mechanism at the same time. An example for systemd:
265    <filename>bluetoothd.service</filename> might get activated either
266    when Bluetooth hardware is plugged in, or when an application
267    accesses its programming interfaces via D-Bus. Or, a print server
268    daemon might get activated when traffic arrives at an IPP port, or
269    when a printer is plugged in, or when a file is queued in the
270    printer spool directory. Even for services that are intended to be
271    started on system bootup unconditionally, it is a good idea to
272    implement some of the various activation schemes outlined below,
273    in order to maximize parallelization. If a daemon implements a
274    D-Bus service or listening socket, implementing the full bus and
275    socket activation scheme allows starting of the daemon with its
276    clients in parallel (which speeds up boot-up), since all its
277    communication channels are established already, and no request is
278    lost because client requests will be queued by the bus system (in
279    case of D-Bus) or the kernel (in case of sockets) until the
280    activation is completed.</para>
281
282    <refsect2>
283      <title>Activation on Boot</title>
284
285      <para>Old-style daemons are usually activated exclusively on
286      boot (and manually by the administrator) via SysV init scripts,
287      as detailed in the <ulink
288      url="http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html">LSB
289      Linux Standard Base Core Specification</ulink>. This method of
290      activation is supported ubiquitously on Linux init systems, both
291      old-style and new-style systems. Among other issues, SysV init
292      scripts have the disadvantage of involving shell scripts in the
293      boot process. New-style init systems generally employ updated
294      versions of activation, both during boot-up and during runtime
295      and using more minimal service description files.</para>
296
297      <para>In systemd, if the developer or administrator wants to
298      make sure that a service or other unit is activated
299      automatically on boot, it is recommended to place a symlink to
300      the unit file in the <filename>.wants/</filename> directory of
301      either <filename>multi-user.target</filename> or
302      <filename>graphical.target</filename>, which are normally used
303      as boot targets at system startup. See
304      <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>
305      for details about the <filename>.wants/</filename> directories,
306      and
307      <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>7</manvolnum></citerefentry>
308      for details about the two boot targets.</para>
309
310    </refsect2>
311
312    <refsect2>
313      <title>Socket-Based Activation</title>
314
315      <para>In order to maximize the possible parallelization and
316      robustness and simplify configuration and development, it is
317      recommended for all new-style daemons that communicate via
318      listening sockets to employ socket-based activation. In a
319      socket-based activation scheme, the creation and binding of the
320      listening socket as primary communication channel of daemons to
321      local (and sometimes remote) clients is moved out of the daemon
322      code and into the init system. Based on per-daemon
323      configuration, the init system installs the sockets and then
324      hands them off to the spawned process as soon as the respective
325      daemon is to be started. Optionally, activation of the service
326      can be delayed until the first inbound traffic arrives at the
327      socket to implement on-demand activation of daemons. However,
328      the primary advantage of this scheme is that all providers and
329      all consumers of the sockets can be started in parallel as soon
330      as all sockets are established. In addition to that, daemons can
331      be restarted with losing only a minimal number of client
332      transactions, or even any client request at all (the latter is
333      particularly true for state-less protocols, such as DNS or
334      syslog), because the socket stays bound and accessible during
335      the restart, and all requests are queued while the daemon cannot
336      process them.</para>
337
338      <para>New-style daemons which support socket activation must be
339      able to receive their sockets from the init system instead of
340      creating and binding them themselves. For details about the
341      programming interfaces for this scheme provided by systemd, see
342      <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>
343      and
344      <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>.
345      For details about porting existing daemons to socket-based
346      activation, see below. With minimal effort, it is possible to
347      implement socket-based activation in addition to traditional
348      internal socket creation in the same codebase in order to
349      support both new-style and old-style init systems from the same
350      daemon binary.</para>
351
352      <para>systemd implements socket-based activation via
353      <filename>.socket</filename> units, which are described in
354      <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry>.
355      When configuring socket units for socket-based activation, it is
356      essential that all listening sockets are pulled in by the
357      special target unit <filename>sockets.target</filename>. It is
358      recommended to place a
359      <varname>WantedBy=sockets.target</varname> directive in the
360      [Install] section to automatically add such a
361      dependency on installation of a socket unit. Unless
362      <varname>DefaultDependencies=no</varname> is set, the necessary
363      ordering dependencies are implicitly created for all socket
364      units. For more information about
365      <filename>sockets.target</filename>, see
366      <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>7</manvolnum></citerefentry>.
367      It is not necessary or recommended to place any additional
368      dependencies on socket units (for example from
369      <filename>multi-user.target</filename> or suchlike) when one is
370      installed in <filename>sockets.target</filename>.</para>
371    </refsect2>
372
373    <refsect2>
374      <title>Bus-Based Activation</title>
375
376      <para>When the D-Bus IPC system is used for communication with
377      clients, new-style daemons should employ bus activation so that
378      they are automatically activated when a client application
379      accesses their IPC interfaces. This is configured in D-Bus
380      service files (not to be confused with systemd service unit
381      files!). To ensure that D-Bus uses systemd to start-up and
382      maintain the daemon, use the <varname>SystemdService=</varname>
383      directive in these service files to configure the matching
384      systemd service for a D-Bus service. e.g.: For a D-Bus service
385      whose D-Bus activation file is named
386      <filename>org.freedesktop.RealtimeKit.service</filename>, make
387      sure to set
388      <varname>SystemdService=rtkit-daemon.service</varname> in that
389      file to bind it to the systemd service
390      <filename>rtkit-daemon.service</filename>. This is needed to
391      make sure that the daemon is started in a race-free fashion when
392      activated via multiple mechanisms simultaneously.</para>
393    </refsect2>
394
395    <refsect2>
396      <title>Device-Based Activation</title>
397
398      <para>Often, daemons that manage a particular type of hardware
399      should be activated only when the hardware of the respective
400      kind is plugged in or otherwise becomes available. In a
401      new-style init system, it is possible to bind activation to
402      hardware plug/unplug events. In systemd, kernel devices
403      appearing in the sysfs/udev device tree can be exposed as units
404      if they are tagged with the string <literal>systemd</literal>.
405      Like any other kind of unit, they may then pull in other units
406      when activated (i.e. plugged in) and thus implement device-based
407      activation. systemd dependencies may be encoded in the udev
408      database via the <varname>SYSTEMD_WANTS=</varname> property. See
409      <citerefentry><refentrytitle>systemd.device</refentrytitle><manvolnum>5</manvolnum></citerefentry>
410      for details. Often, it is nicer to pull in services from devices
411      only indirectly via dedicated targets. Example: Instead of
412      pulling in <filename>bluetoothd.service</filename> from all the
413      various bluetooth dongles and other hardware available, pull in
414      bluetooth.target from them and
415      <filename>bluetoothd.service</filename> from that target. This
416      provides for nicer abstraction and gives administrators the
417      option to enable <filename>bluetoothd.service</filename> via
418      controlling a <filename>bluetooth.target.wants/</filename>
419      symlink uniformly with a command like <command>enable</command>
420      of
421      <citerefentry><refentrytitle>systemctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>
422      instead of manipulating the udev ruleset.</para>
423    </refsect2>
424
425    <refsect2>
426      <title>Path-Based Activation</title>
427
428      <para>Often, runtime of daemons processing spool files or
429      directories (such as a printing system) can be delayed until
430      these file system objects change state, or become non-empty.
431      New-style init systems provide a way to bind service activation
432      to file system changes. systemd implements this scheme via
433      path-based activation configured in <filename>.path</filename>
434      units, as outlined in
435      <citerefentry><refentrytitle>systemd.path</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para>
436    </refsect2>
437
438    <refsect2>
439      <title>Timer-Based Activation</title>
440
441      <para>Some daemons that implement clean-up jobs that are
442      intended to be executed in regular intervals benefit from
443      timer-based activation. In systemd, this is implemented via
444      <filename>.timer</filename> units, as described in
445      <citerefentry><refentrytitle>systemd.timer</refentrytitle><manvolnum>5</manvolnum></citerefentry>.</para>
446    </refsect2>
447
448    <refsect2>
449      <title>Other Forms of Activation</title>
450
451      <para>Other forms of activation have been suggested and implemented in some systems. However, there are
452      often simpler or better alternatives, or they can be put together of combinations of the schemes
453      above. Example: Sometimes, it appears useful to start daemons or <filename>.socket</filename> units
454      when a specific IP address is configured on a network interface, because network sockets shall be bound
455      to the address. However, an alternative to implement this is by utilizing the Linux
456      <constant>IP_FREEBIND</constant>/<constant>IPV6_FREEBIND</constant> socket option, as accessible via
457      <varname>FreeBind=yes</varname> in systemd socket files (see
458      <citerefentry><refentrytitle>systemd.socket</refentrytitle><manvolnum>5</manvolnum></citerefentry> for
459      details). This option, when enabled, allows sockets to be bound to a non-local, not configured IP
460      address, and hence allows bindings to a particular IP address before it actually becomes available,
461      making such an explicit dependency to the configured address redundant. Another often suggested trigger
462      for service activation is low system load. However, here too, a more convincing approach might be to
463      make proper use of features of the operating system, in particular, the CPU or I/O scheduler of
464      Linux. Instead of scheduling jobs from userspace based on monitoring the OS scheduler, it is advisable
465      to leave the scheduling of processes to the OS scheduler itself. systemd provides fine-grained access
466      to the CPU and I/O schedulers. If a process executed by the init system shall not negatively impact the
467      amount of CPU or I/O bandwidth available to other processes, it should be configured with
468      <varname>CPUSchedulingPolicy=idle</varname> and/or
469      <varname>IOSchedulingClass=idle</varname>. Optionally, this may be combined with timer-based activation
470      to schedule background jobs during runtime and with minimal impact on the system, and remove it from
471      the boot phase itself.</para>
472    </refsect2>
473
474  </refsect1>
475  <refsect1>
476    <title>Integration with systemd</title>
477
478    <refsect2>
479      <title>Writing systemd Unit Files</title>
480
481      <para>When writing systemd unit files, it is recommended to
482      consider the following suggestions:</para>
483
484      <orderedlist>
485        <listitem><para>If possible, do not use the
486        <varname>Type=forking</varname> setting in service files. But
487        if you do, make sure to set the PID file path using
488        <varname>PIDFile=</varname>. See
489        <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>
490        for details.</para></listitem>
491
492        <listitem><para>If your daemon registers a D-Bus name on the
493        bus, make sure to use <varname>Type=dbus</varname> in the
494        service file if possible.</para></listitem>
495
496        <listitem><para>Make sure to set a good human-readable
497        description string with
498        <varname>Description=</varname>.</para></listitem>
499
500        <listitem><para>Do not disable
501        <varname>DefaultDependencies=</varname>, unless you really
502        know what you do and your unit is involved in early boot or
503        late system shutdown.</para></listitem>
504
505        <listitem><para>Normally, little if any dependencies should
506        need to be defined explicitly. However, if you do configure
507        explicit dependencies, only refer to unit names listed on
508        <citerefentry><refentrytitle>systemd.special</refentrytitle><manvolnum>7</manvolnum></citerefentry>
509        or names introduced by your own package to keep the unit file
510        operating system-independent.</para></listitem>
511
512        <listitem><para>Make sure to include an
513        [Install] section including installation
514        information for the unit file. See
515        <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>
516        for details. To activate your service on boot, make sure to
517        add a <varname>WantedBy=multi-user.target</varname> or
518        <varname>WantedBy=graphical.target</varname> directive. To
519        activate your socket on boot, make sure to add
520        <varname>WantedBy=sockets.target</varname>. Usually, you also
521        want to make sure that when your service is installed, your
522        socket is installed too, hence add
523        <varname>Also=foo.socket</varname> in your service file
524        <filename>foo.service</filename>, for a hypothetical program
525        <filename>foo</filename>.</para></listitem>
526
527      </orderedlist>
528    </refsect2>
529
530    <refsect2>
531      <title>Installing systemd Service Files</title>
532
533      <para>At the build installation time (e.g. <command>make
534      install</command> during package build), packages are
535      recommended to install their systemd unit files in the directory
536      returned by <command>pkg-config systemd
537      --variable=systemdsystemunitdir</command> (for system services)
538      or <command>pkg-config systemd
539      --variable=systemduserunitdir</command> (for user services).
540      This will make the services available in the system on explicit
541      request but not activate them automatically during boot.
542      Optionally, during package installation (e.g. <command>rpm
543      -i</command> by the administrator), symlinks should be created
544      in the systemd configuration directories via the
545      <command>enable</command> command of the
546      <citerefentry><refentrytitle>systemctl</refentrytitle><manvolnum>1</manvolnum></citerefentry>
547      tool to activate them automatically on boot.</para>
548
549      <para>Packages using
550      <citerefentry project='die-net'><refentrytitle>autoconf</refentrytitle><manvolnum>1</manvolnum></citerefentry>
551      are recommended to use a configure script
552      excerpt like the following to determine the
553      unit installation path during source
554      configuration:</para>
555
556      <programlisting>PKG_PROG_PKG_CONFIG
557AC_ARG_WITH([systemdsystemunitdir],
558     [AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files])],,
559     [with_systemdsystemunitdir=auto])
560AS_IF([test "x$with_systemdsystemunitdir" = "xyes" -o "x$with_systemdsystemunitdir" = "xauto"], [
561     def_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)
562
563     AS_IF([test "x$def_systemdsystemunitdir" = "x"],
564   [AS_IF([test "x$with_systemdsystemunitdir" = "xyes"],
565    [AC_MSG_ERROR([systemd support requested but pkg-config unable to query systemd package])])
566    with_systemdsystemunitdir=no],
567   [with_systemdsystemunitdir="$def_systemdsystemunitdir"])])
568AS_IF([test "x$with_systemdsystemunitdir" != "xno"],
569      [AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])])
570AM_CONDITIONAL([HAVE_SYSTEMD], [test "x$with_systemdsystemunitdir" != "xno"])</programlisting>
571
572      <para>This snippet allows automatic
573      installation of the unit files on systemd
574      machines, and optionally allows their
575      installation even on machines lacking
576      systemd. (Modification of this snippet for the
577      user unit directory is left as an exercise for the
578      reader.)</para>
579
580      <para>Additionally, to ensure that
581      <command>make distcheck</command> continues to
582      work, it is recommended to add the following
583      to the top-level <filename>Makefile.am</filename>
584      file in
585      <citerefentry project='die-net'><refentrytitle>automake</refentrytitle><manvolnum>1</manvolnum></citerefentry>-based
586      projects:</para>
587
588      <programlisting>AM_DISTCHECK_CONFIGURE_FLAGS = \
589  --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)</programlisting>
590
591      <para>Finally, unit files should be installed in the system with an automake excerpt like the following:</para>
592
593      <programlisting>if HAVE_SYSTEMD
594systemdsystemunit_DATA = \
595  foobar.socket \
596  foobar.service
597endif</programlisting>
598
599      <para>In the
600      <citerefentry project='die-net'><refentrytitle>rpm</refentrytitle><manvolnum>8</manvolnum></citerefentry>
601      <filename>.spec</filename> file, use snippets like the following
602      to enable/disable the service during
603      installation/deinstallation. This makes use of the RPM macros
604      shipped along systemd. Consult the packaging guidelines of your
605      distribution for details and the equivalent for other package
606      managers.</para>
607
608      <para>At the top of the file:</para>
609
610      <programlisting>BuildRequires: systemd
611%{?systemd_requires}</programlisting>
612
613      <para>And as scriptlets, further down:</para>
614
615      <programlisting>%post
616%systemd_post foobar.service foobar.socket
617
618%preun
619%systemd_preun foobar.service foobar.socket
620
621%postun
622%systemd_postun</programlisting>
623
624      <para>If the service shall be restarted during upgrades, replace
625      the <literal>%postun</literal> scriptlet above with the
626      following:</para>
627
628      <programlisting>%postun
629%systemd_postun_with_restart foobar.service</programlisting>
630
631      <para>Note that <literal>%systemd_post</literal> and
632      <literal>%systemd_preun</literal> expect the names of all units
633      that are installed/removed as arguments, separated by spaces.
634      <literal>%systemd_postun</literal> expects no arguments.
635      <literal>%systemd_postun_with_restart</literal> expects the
636      units to restart as arguments.</para>
637
638      <para>To facilitate upgrades from a package version that shipped
639      only SysV init scripts to a package version that ships both a
640      SysV init script and a native systemd service file, use a
641      fragment like the following:</para>
642
643      <programlisting>%triggerun -- foobar &lt; 0.47.11-1
644if /sbin/chkconfig --level 5 foobar ; then
645  /bin/systemctl --no-reload enable foobar.service foobar.socket >/dev/null 2>&amp;1 || :
646fi</programlisting>
647
648      <para>Where 0.47.11-1 is the first package version that includes
649      the native unit file. This fragment will ensure that the first
650      time the unit file is installed, it will be enabled if and only
651      if the SysV init script is enabled, thus making sure that the
652      enable status is not changed. Note that
653      <command>chkconfig</command> is a command specific to Fedora
654      which can be used to check whether a SysV init script is
655      enabled. Other operating systems will have to use different
656      commands here.</para>
657    </refsect2>
658  </refsect1>
659
660  <refsect1>
661    <title>Porting Existing Daemons</title>
662
663    <para>Since new-style init systems such as systemd are compatible
664    with traditional SysV init systems, it is not strictly necessary
665    to port existing daemons to the new style. However, doing so
666    offers additional functionality to the daemons as well as
667    simplifying integration into new-style init systems.</para>
668
669    <para>To port an existing SysV compatible daemon, the following
670    steps are recommended:</para>
671
672    <orderedlist>
673      <listitem><para>If not already implemented, add an optional
674      command line switch to the daemon to disable daemonization. This
675      is useful not only for using the daemon in new-style init
676      systems, but also to ease debugging.</para></listitem>
677
678      <listitem><para>If the daemon offers interfaces to other
679      software running on the local system via local
680      <constant>AF_UNIX</constant> sockets, consider implementing
681      socket-based activation (see above). Usually, a minimal patch is
682      sufficient to implement this: Extend the socket creation in the
683      daemon code so that
684      <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>
685      is checked for already passed sockets first. If sockets are
686      passed (i.e. when <function>sd_listen_fds()</function> returns a
687      positive value), skip the socket creation step and use the
688      passed sockets. Secondly, ensure that the file system socket
689      nodes for local <constant>AF_UNIX</constant> sockets used in the
690      socket-based activation are not removed when the daemon shuts
691      down, if sockets have been passed. Third, if the daemon normally
692      closes all remaining open file descriptors as part of its
693      initialization, the sockets passed from the init system must be
694      spared. Since new-style init systems guarantee that no left-over
695      file descriptors are passed to executed processes, it might be a
696      good choice to simply skip the closing of all remaining open
697      file descriptors if sockets are passed.</para></listitem>
698
699      <listitem><para>Write and install a systemd unit file for the
700      service (and the sockets if socket-based activation is used, as
701      well as a path unit file, if the daemon processes a spool
702      directory), see above for details.</para></listitem>
703
704      <listitem><para>If the daemon exposes interfaces via D-Bus,
705      write and install a D-Bus activation file for the service, see
706      above for details.</para></listitem>
707    </orderedlist>
708  </refsect1>
709
710  <refsect1>
711    <title>Placing Daemon Data</title>
712
713    <para>It is recommended to follow the general guidelines for
714    placing package files, as discussed in
715    <citerefentry><refentrytitle>file-hierarchy</refentrytitle><manvolnum>7</manvolnum></citerefentry>.</para>
716  </refsect1>
717
718  <refsect1>
719    <title>See Also</title>
720    <para>
721      <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>,
722      <citerefentry><refentrytitle>sd-daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
723      <citerefentry><refentrytitle>sd_listen_fds</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
724      <citerefentry><refentrytitle>sd_notify</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
725      <citerefentry><refentrytitle>daemon</refentrytitle><manvolnum>3</manvolnum></citerefentry>,
726      <citerefentry><refentrytitle>systemd.service</refentrytitle><manvolnum>5</manvolnum></citerefentry>,
727      <citerefentry><refentrytitle>file-hierarchy</refentrytitle><manvolnum>7</manvolnum></citerefentry>
728    </para>
729  </refsect1>
730
731</refentry>
732