File: daemon.html

package info (click to toggle)
systemd 215-17
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 49,568 kB
  • sloc: ansic: 192,789; xml: 39,586; sh: 13,002; makefile: 4,700; perl: 1,461; python: 1,355
file content (689 lines) | stat: -rw-r--r-- 53,991 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>daemon</title><meta name="generator" content="DocBook XSL Stylesheets V1.78.1"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><style>
    a.headerlink {
      color: #c60f0f;
      font-size: 0.8em;
      padding: 0 4px 0 4px;
      text-decoration: none;
      visibility: hidden;
    }

    a.headerlink:hover {
      background-color: #c60f0f;
      color: white;
    }

    h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, dt:hover > a.headerlink {
      visibility: visible;
    }
  </style><a href="index.html">Index </a>·
  <a href="systemd.directives.html">Directives </a>·
  <a href="../python-systemd/index.html">Python </a>·
  <a href="../libudev/index.html">libudev </a>·
  <a href="../libudev/index.html">gudev </a><span style="float:right">systemd 215</span><hr><div class="refentry"><a name="daemon"></a><div class="titlepage"></div><div class="refnamediv"><h2>Name</h2><p>daemon — Writing and packaging system daemons</p></div><div class="refsect1"><a name="idm214179512176"></a><h2 id="Description">Description<a class="headerlink" title="Permalink to this headline" href="#Description">¶</a></h2><p>A daemon is a service process that runs in the
                background and supervises the system or provides
                functionality to other processes. Traditionally,
                daemons are implemented following a scheme originating
                in SysV Unix. Modern daemons should follow a simpler
                yet more powerful scheme (here called "new-style"
                daemons), as implemented by
                <a href="systemd.html"><span class="citerefentry"><span class="refentrytitle">systemd</span>(1)</span></a>. This
                manual page covers both schemes, and in
                particular includes recommendations for daemons that
                shall be included in the systemd init system.</p><div class="refsect2"><a name="idm214177063248"></a><h3 id="SysV Daemons">SysV Daemons<a class="headerlink" title="Permalink to this headline" href="#SysV%20Daemons">¶</a></h3><p>When a traditional SysV daemon
                        starts, it should execute the following steps
                        as part of the initialization. Note that these
                        steps are unnecessary for new-style daemons (see below),
                        and should only be implemented if compatibility
                        with SysV is essential.</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>Close all open file
                                descriptors except standard input, output,
                                and error (i.e. the first three file
                                descriptors 0, 1, 2). This ensures
                                that no accidentally passed file
                                descriptor stays around in the daemon
                                process. On Linux, this is best
                                implemented by iterating through
                                <code class="filename">/proc/self/fd</code>,
                                with a fallback of iterating from file
                                descriptor 3 to the value returned by
                                <code class="function">getrlimit()</code> for
                                RLIMIT_NOFILE.</p></li><li class="listitem"><p>Reset all signal
                                handlers to their default. This is
                                best done by iterating through the
                                available signals up to the limit of
                                _NSIG and resetting them to
                                <code class="constant">SIG_DFL</code>.</p></li><li class="listitem"><p>Reset the signal mask
                                using
                                <code class="function">sigprocmask()</code>.</p></li><li class="listitem"><p>Sanitize the
                                environment block, removing or
                                resetting environment variables that
                                might negatively impact daemon
                                runtime.</p></li><li class="listitem"><p>Call <code class="function">fork()</code>,
                                to create a background
                                process.</p></li><li class="listitem"><p>In the child, call
                                <code class="function">setsid()</code> to
                                detach from any terminal and create an
                                independent session.</p></li><li class="listitem"><p>In the child, call
                                <code class="function">fork()</code> again, to
                                ensure that the daemon can never re-acquire
                                a terminal again.</p></li><li class="listitem"><p>Call <code class="function">exit()</code> in the
                                first child, so that only the second
                                child (the actual daemon process)
                                stays around. This ensures that the
                                daemon process is re-parented to
                                init/PID 1, as all daemons should
                                be.</p></li><li class="listitem"><p>In the daemon process,
                                connect <code class="filename">/dev/null</code>
                                to standard input, output, and error.
                                </p></li><li class="listitem"><p>In the daemon process,
                                reset the umask to 0, so that the file
                                modes passed to <code class="function">open()</code>, <code class="function">mkdir()</code> and
                                suchlike directly control the access
                                mode of the created files and
                                directories.</p></li><li class="listitem"><p>In the daemon process,
                                change the current directory to the
                                root directory (/), in order to avoid
                                that the daemon involuntarily
                                blocks mount points from being
                                unmounted.</p></li><li class="listitem"><p>In the daemon process,
                                write the daemon PID (as returned by
                                <code class="function">getpid()</code>) to a
                                PID file, for example
                                <code class="filename">/run/foobar.pid</code>
                                (for a hypothetical daemon "foobar")
                                to ensure that the daemon cannot be
                                started more than once. This must be
                                implemented in race-free fashion so
                                that the PID file is only updated when
                                it is verified at the same time that
                                the PID previously stored in the PID
                                file no longer exists or belongs to a
                                foreign process.</p></li><li class="listitem"><p>In the daemon process,
                                drop privileges, if possible and
                                applicable.</p></li><li class="listitem"><p>From the daemon
                                process, notify the original process
                                started that initialization is
                                complete. This can be implemented via
                                an unnamed pipe or similar
                                communication channel that is created
                                before the first
                                <code class="function">fork()</code> and hence
                                available in both the original and the
                                daemon process.</p></li><li class="listitem"><p>Call
                                <code class="function">exit()</code> in the
                                original process. The process that
                                invoked the daemon must be able to
                                rely on that this
                                <code class="function">exit()</code> happens
                                after initialization is complete and
                                all external communication channels
                                are established and
                                accessible.</p></li></ol></div><p>The BSD <code class="function">daemon()</code> function should not be
                        used, as it implements only a subset of these steps.</p><p>A daemon that needs to provide
                        compatibility with SysV systems should
                        implement the scheme pointed out
                        above. However, it is recommended to make this
                        behavior optional and configurable via a
                        command line argument to ease debugging as
                        well as to simplify integration into systems
                        using systemd.</p></div><div class="refsect2"><a name="idm214175728384"></a><h3 id="New-Style Daemons">New-Style Daemons<a class="headerlink" title="Permalink to this headline" href="#New-Style%20Daemons">¶</a></h3><p>Modern services for Linux should be
                        implemented as new-style daemons. This makes it
                        easier to supervise and control them at
                        runtime and simplifies their
                        implementation.</p><p>For developing a new-style daemon, none
                        of the initialization steps recommended for
                        SysV daemons need to be implemented. New-style
                        init systems such as systemd make all of them
                        redundant. Moreover, since some of these steps
                        interfere with process monitoring, file
                        descriptor passing and other functionality of
                        the init system, it is recommended not to
                        execute them when run as new-style
                        service.</p><p>Note that new-style init systems
                        guarantee execution of daemon processes in a
                        clean process context: it is guaranteed that
                        the environment block is sanitized, that the
                        signal handlers and mask is reset and that no
                        left-over file descriptors are passed. Daemons
                        will be executed in their own session, with
                        standard input/output/error connected to
                        <code class="filename">/dev/null</code> unless
                        otherwise configured. The umask is reset.
                        </p><p>It is recommended for new-style daemons
                        to implement the following:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>If <code class="constant">SIGTERM</code> is
                                received, shut down the daemon and
                                exit cleanly.</p></li><li class="listitem"><p>If <code class="constant">SIGHUP</code> is received,
                                reload the configuration files, if
                                this applies.</p></li><li class="listitem"><p>Provide a correct exit
                                code from the main daemon process, as
                                this is used by the init system to
                                detect service errors and problems. It
                                is recommended to follow the exit code
                                scheme as defined in the <a class="ulink" href="http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html" target="_top">LSB
                                recommendations for SysV init
                                scripts</a>.</p></li><li class="listitem"><p>If possible and
                                applicable, expose the daemon's control
                                interface via the D-Bus IPC system and
                                grab a bus name as last step of
                                initialization.</p></li><li class="listitem"><p>For integration in
                                systemd, provide a
                                <code class="filename">.service</code> unit
                                file that carries information about
                                starting, stopping and otherwise
                                maintaining the daemon. See
                                <a href="systemd.service.html"><span class="citerefentry"><span class="refentrytitle">systemd.service</span>(5)</span></a>
                                for details.</p></li><li class="listitem"><p>As much as possible,
                                rely on the init system's
                                functionality to limit the access of
                                the daemon to files, services and
                                other resources, i.e. in the case of
                                systemd, rely on systemd's resource
                                limit control instead of implementing
                                your own, rely on systemd's privilege
                                dropping code instead of implementing
                                it in the daemon, and similar. See
                                <a href="systemd.exec.html"><span class="citerefentry"><span class="refentrytitle">systemd.exec</span>(5)</span></a>
                                for the available
                                controls.</p></li><li class="listitem"><p>If D-Bus is used, make
                                your daemon bus-activatable by
                                supplying a D-Bus service activation
                                configuration file. This has multiple
                                advantages: your daemon may be started
                                lazily on-demand; it may be started in
                                parallel to other daemons requiring it
                                -- which maximizes parallelization and
                                boot-up speed; your daemon can be
                                restarted on failure without losing
                                any bus requests, as the bus queues
                                requests for activatable services. See
                                below for details.</p></li><li class="listitem"><p>If your daemon
                                provides services to other local
                                processes or remote clients via a
                                socket, it should be made
                                socket-activatable following the
                                scheme pointed out below. Like D-Bus
                                activation, this enables on-demand
                                starting of services as well as it
                                allows improved parallelization of
                                service start-up. Also, for state-less
                                protocols (such as syslog, DNS), a
                                daemon implementing socket-based
                                activation can be restarted without
                                losing a single request. See below for
                                details.</p></li><li class="listitem"><p>If applicable, a daemon
                                should notify the init system about
                                startup completion or status updates
                                via the
                                <a href="sd_notify.html"><span class="citerefentry"><span class="refentrytitle">sd_notify</span>(3)</span></a>
                                interface.</p></li><li class="listitem"><p>Instead of using the
                                <code class="function">syslog()</code> call to
                                log directly to the system syslog
                                service, a new-style daemon may choose
                                to simply log to standard error via
                                <code class="function">fprintf()</code>, which
                                is then forwarded to syslog by the
                                init system. If log priorities are
                                necessary, these can be encoded by
                                prefixing individual log lines with
                                strings like "&lt;4&gt;" (for log
                                priority 4 "WARNING" in the syslog
                                priority scheme), following a similar
                                style as the Linux kernel's
                                <code class="function">printk()</code> priority
                                system. For details, see
                                <a href="sd-daemon.html"><span class="citerefentry"><span class="refentrytitle">sd-daemon</span>(3)</span></a>
                                and
                                <a href="systemd.exec.html"><span class="citerefentry"><span class="refentrytitle">systemd.exec</span>(5)</span></a>.</p></li></ol></div><p>These recommendations are similar but
                        not identical to the <a class="ulink" href="https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html" target="_top">Apple
                        MacOS X Daemon Requirements</a>.</p></div></div><div class="refsect1"><a name="idm214178358368"></a><h2 id="Activation">Activation<a class="headerlink" title="Permalink to this headline" href="#Activation">¶</a></h2><p>New-style init systems provide multiple
                additional mechanisms to activate services, as
                detailed below. It is common that services are
                configured to be activated via more than one mechanism
                at the same time. An example for systemd:
                <code class="filename">bluetoothd.service</code> might get
                activated either when Bluetooth hardware is plugged
                in, or when an application accesses its programming
                interfaces via D-Bus. Or, a print server daemon might
                get activated when traffic arrives at an IPP port, or
                when a printer is plugged in, or when a file is queued
                in the printer spool directory. Even for services that
                are intended to be started on system bootup
                unconditionally, it is a good idea to implement some of
                the various activation schemes outlined below, in
                order to maximize parallelization. If a daemon
                implements a D-Bus service or listening socket,
                implementing the full bus and socket activation scheme
                allows starting of the daemon with its clients in
                parallel (which speeds up boot-up), since all its
                communication channels are established already, and no
                request is lost because client requests will be queued
                by the bus system (in case of D-Bus) or the kernel (in
                case of sockets) until the activation is
                completed.</p><div class="refsect2"><a name="idm214177474608"></a><h3 id="Activation on Boot">Activation on Boot<a class="headerlink" title="Permalink to this headline" href="#Activation%20on%20Boot">¶</a></h3><p>Old-style daemons are usually activated
                        exclusively on boot (and manually by the
                        administrator) via SysV init scripts, as
                        detailed in the <a class="ulink" href="http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html" target="_top">LSB
                        Linux Standard Base Core
                        Specification</a>. This method of
                        activation is supported ubiquitously on Linux
                        init systems, both old-style and new-style
                        systems. Among other issues, SysV init scripts
                        have the disadvantage of involving shell
                        scripts in the boot process. New-style init
                        systems generally employ updated versions of
                        activation, both during boot-up and during
                        runtime and using more minimal service
                        description files.</p><p>In systemd, if the developer or
                        administrator wants to make sure that a service or
                        other unit is activated automatically on boot,
                        it is recommended to place a symlink to the
                        unit file in the <code class="filename">.wants/</code>
                        directory of either
                        <code class="filename">multi-user.target</code> or
                        <code class="filename">graphical.target</code>, which
                        are normally used as boot targets at system
                        startup. See
                        <a href="systemd.unit.html"><span class="citerefentry"><span class="refentrytitle">systemd.unit</span>(5)</span></a>
                        for details about the
                        <code class="filename">.wants/</code> directories, and
                        <a href="systemd.special.html"><span class="citerefentry"><span class="refentrytitle">systemd.special</span>(7)</span></a>
                        for details about the two boot targets.</p></div><div class="refsect2"><a name="idm214175963792"></a><h3 id="Socket-Based Activation">Socket-Based Activation<a class="headerlink" title="Permalink to this headline" href="#Socket-Based%20Activation">¶</a></h3><p>In order to maximize the possible
                        parallelization and robustness and simplify
                        configuration and development, it is
                        recommended for all new-style daemons that
                        communicate via listening sockets to employ
                        socket-based activation. In a socket-based
                        activation scheme, the creation and binding of
                        the listening socket as primary communication
                        channel of daemons to local (and sometimes
                        remote) clients is moved out of the daemon
                        code and into the init system. Based on
                        per-daemon configuration, the init system
                        installs the sockets and then hands them off
                        to the spawned process as soon as the
                        respective daemon is to be started.
                        Optionally, activation of the service can be
                        delayed until the first inbound traffic
                        arrives at the socket to implement on-demand
                        activation of daemons. However, the primary
                        advantage of this scheme is that all providers
                        and all consumers of the sockets can be
                        started in parallel as soon as all sockets
                        are established. In addition to that, daemons
                        can be restarted with losing only a minimal
                        number of client transactions, or even any
                        client request at all (the latter is
                        particularly true for state-less protocols,
                        such as DNS or syslog), because the socket
                        stays bound and accessible during the restart,
                        and all requests are queued while the daemon
                        cannot process them.</p><p>New-style daemons which support socket
                        activation must be able to receive their
                        sockets from the init system instead of
                        creating and binding them themselves. For
                        details about the programming interfaces for
                        this scheme provided by systemd, see
                        <a href="sd_listen_fds.html"><span class="citerefentry"><span class="refentrytitle">sd_listen_fds</span>(3)</span></a>
                        and
                        <a href="sd-daemon.html"><span class="citerefentry"><span class="refentrytitle">sd-daemon</span>(3)</span></a>. For
                        details about porting existing daemons to
                        socket-based activation, see below. With
                        minimal effort, it is possible to implement
                        socket-based activation in addition to
                        traditional internal socket creation in the
                        same codebase in order to support both
                        new-style and old-style init systems from the
                        same daemon binary.</p><p>systemd implements socket-based
                        activation via <code class="filename">.socket</code>
                        units, which are described in
                        <a href="systemd.socket.html"><span class="citerefentry"><span class="refentrytitle">systemd.socket</span>(5)</span></a>. When
                        configuring socket units for socket-based
                        activation, it is essential that all listening
                        sockets are pulled in by the special target
                        unit <code class="filename">sockets.target</code>. It
                        is recommended to place a
                        <code class="varname">WantedBy=sockets.target</code>
                        directive in the "<code class="literal">[Install]</code>"
                        section to automatically add such a
                        dependency on installation of a socket
                        unit. Unless
                        <code class="varname">DefaultDependencies=no</code> is
                        set, the necessary ordering dependencies are
                        implicitly created for all socket units. For
                        more information about
                        <code class="filename">sockets.target</code>, see
                        <a href="systemd.special.html"><span class="citerefentry"><span class="refentrytitle">systemd.special</span>(7)</span></a>. It
                        is not necessary or recommended to place any
                        additional dependencies on socket units (for
                        example from
                        <code class="filename">multi-user.target</code> or
                        suchlike) when one is installed in
                        <code class="filename">sockets.target</code>.</p></div><div class="refsect2"><a name="idm214176756752"></a><h3 id="Bus-Based Activation">Bus-Based Activation<a class="headerlink" title="Permalink to this headline" href="#Bus-Based%20Activation">¶</a></h3><p>When the D-Bus IPC system is used for
                        communication with clients, new-style daemons
                        should employ bus activation so that they are
                        automatically activated when a client
                        application accesses their IPC
                        interfaces. This is configured in D-Bus
                        service files (not to be confused with systemd
                        service unit files!). To ensure that D-Bus
                        uses systemd to start-up and maintain the
                        daemon, use the
                        <code class="varname">SystemdService=</code> directive
                        in these service files to configure the
                        matching systemd service for a D-Bus
                        service. e.g.: For a D-Bus service whose D-Bus
                        activation file is named
                        <code class="filename">org.freedesktop.RealtimeKit.service</code>,
                        make sure to set
                        <code class="varname">SystemdService=rtkit-daemon.service</code>
                        in that file to bind it to the systemd
                        service
                        <code class="filename">rtkit-daemon.service</code>. This
                        is needed to make sure that the daemon is
                        started in a race-free fashion when activated
                        via multiple mechanisms simultaneously.</p></div><div class="refsect2"><a name="idm214178044384"></a><h3 id="Device-Based Activation">Device-Based Activation<a class="headerlink" title="Permalink to this headline" href="#Device-Based%20Activation">¶</a></h3><p>Often, daemons that manage a particular
                        type of hardware should be activated only when
                        the hardware of the respective kind is plugged
                        in or otherwise becomes available. In a
                        new-style init system, it is possible to bind
                        activation to hardware plug/unplug events. In
                        systemd, kernel devices appearing in the
                        sysfs/udev device tree can be exposed as units
                        if they are tagged with the string
                        "<code class="literal">systemd</code>". Like any other
                        kind of unit, they may then pull in other units
                        when activated (i.e. plugged in) and thus
                        implement device-based activation. systemd
                        dependencies may be encoded in the udev
                        database via the
                        <code class="varname">SYSTEMD_WANTS=</code>
                        property. See
                        <a href="systemd.device.html"><span class="citerefentry"><span class="refentrytitle">systemd.device</span>(5)</span></a>
                        for details. Often, it is nicer to pull in
                        services from devices only indirectly via
                        dedicated targets. Example: Instead of pulling
                        in <code class="filename">bluetoothd.service</code>
                        from all the various bluetooth dongles and
                        other hardware available, pull in
                        bluetooth.target from them and
                        <code class="filename">bluetoothd.service</code> from
                        that target. This provides for nicer
                        abstraction and gives administrators the
                        option to enable
                        <code class="filename">bluetoothd.service</code> via
                        controlling a
                        <code class="filename">bluetooth.target.wants/</code>
                        symlink uniformly with a command like
                        <span class="command"><strong>enable</strong></span> of
                        <a href="systemctl.html"><span class="citerefentry"><span class="refentrytitle">systemctl</span>(1)</span></a>
                        instead of manipulating the udev
                        ruleset.</p></div><div class="refsect2"><a name="idm214178026080"></a><h3 id="Path-Based Activation">Path-Based Activation<a class="headerlink" title="Permalink to this headline" href="#Path-Based%20Activation">¶</a></h3><p>Often, runtime of daemons processing
                        spool files or directories (such as a printing
                        system) can be delayed until these file system
                        objects change state, or become
                        non-empty. New-style init systems provide a
                        way to bind service activation to file system
                        changes. systemd implements this scheme via
                        path-based activation configured in
                        <code class="filename">.path</code> units, as outlined
                        in
                        <a href="systemd.path.html"><span class="citerefentry"><span class="refentrytitle">systemd.path</span>(5)</span></a>.</p></div><div class="refsect2"><a name="idm214176776224"></a><h3 id="Timer-Based Activation">Timer-Based Activation<a class="headerlink" title="Permalink to this headline" href="#Timer-Based%20Activation">¶</a></h3><p>Some daemons that implement clean-up
                        jobs that are intended to be executed in
                        regular intervals benefit from timer-based
                        activation. In systemd, this is implemented
                        via <code class="filename">.timer</code> units, as
                        described in
                        <a href="systemd.timer.html"><span class="citerefentry"><span class="refentrytitle">systemd.timer</span>(5)</span></a>.</p></div><div class="refsect2"><a name="idm214176252752"></a><h3 id="Other Forms of Activation">Other Forms of Activation<a class="headerlink" title="Permalink to this headline" href="#Other%20Forms%20of%20Activation">¶</a></h3><p>Other forms of activation have been
                        suggested and implemented in some
                        systems. However, there are often simpler or
                        better alternatives, or they can be put
                        together of combinations of the schemes
                        above. Example: Sometimes, it appears useful to
                        start daemons or <code class="filename">.socket</code>
                        units when a specific IP address is configured
                        on a network interface, because network
                        sockets shall be bound to the
                        address. However, an alternative to implement
                        this is by utilizing the Linux IP_FREEBIND
                        socket option, as accessible via
                        <code class="varname">FreeBind=yes</code> in systemd
                        socket files (see
                        <a href="systemd.socket.html"><span class="citerefentry"><span class="refentrytitle">systemd.socket</span>(5)</span></a>
                        for details). This option, when enabled,
                        allows sockets to be bound to a non-local, not
                        configured IP address, and hence allows
                        bindings to a particular IP address before it
                        actually becomes available, making such an
                        explicit dependency to the configured address
                        redundant. Another often suggested trigger for
                        service activation is low system
                        load. However, here too, a more convincing
                        approach might be to make proper use of
                        features of the operating system, in
                        particular, the CPU or IO scheduler of
                        Linux. Instead of scheduling jobs from
                        userspace based on monitoring the OS
                        scheduler, it is advisable to leave the
                        scheduling of processes to the OS scheduler
                        itself. systemd provides fine-grained access
                        to the CPU and IO schedulers. If a process
                        executed by the init system shall not
                        negatively impact the amount of CPU or IO
                        bandwidth available to other processes, it
                        should be configured with
                        <code class="varname">CPUSchedulingPolicy=idle</code>
                        and/or
                        <code class="varname">IOSchedulingClass=idle</code>. Optionally,
                        this may be combined with timer-based
                        activation to schedule background jobs during
                        runtime and with minimal impact on the system,
                        and remove it from the boot phase
                        itself.</p></div></div><div class="refsect1"><a name="idm214176372608"></a><h2 id="Integration with Systemd">Integration with Systemd<a class="headerlink" title="Permalink to this headline" href="#Integration%20with%20Systemd">¶</a></h2><div class="refsect2"><a name="idm214178809840"></a><h3 id="Writing Systemd Unit Files">Writing Systemd Unit Files<a class="headerlink" title="Permalink to this headline" href="#Writing%20Systemd%20Unit%20Files">¶</a></h3><p>When writing systemd unit files, it is
                        recommended to consider the following
                        suggestions:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>If possible, do not use
                                the <code class="varname">Type=forking</code>
                                setting in service files. But if you
                                do, make sure to set the PID file path
                                using <code class="varname">PIDFile=</code>. See
                                <a href="systemd.service.html"><span class="citerefentry"><span class="refentrytitle">systemd.service</span>(5)</span></a>
                                for details.</p></li><li class="listitem"><p>If your daemon
                                registers a D-Bus name on the bus,
                                make sure to use
                                <code class="varname">Type=dbus</code> in the
                                service file if
                                possible.</p></li><li class="listitem"><p>Make sure to set a
                                good human-readable description string
                                with
                                <code class="varname">Description=</code>.</p></li><li class="listitem"><p>Do not disable
                                <code class="varname">DefaultDependencies=</code>,
                                unless you really know what you do and
                                your unit is involved in early boot or
                                late system shutdown.</p></li><li class="listitem"><p>Normally, little if
                                any dependencies should need to
                                be defined explicitly. However, if you
                                do configure explicit dependencies, only refer to
                                unit names listed on
                                <a href="systemd.special.html"><span class="citerefentry"><span class="refentrytitle">systemd.special</span>(7)</span></a>
                                or names introduced by your own
                                package to keep the unit file
                                operating
                                system-independent.</p></li><li class="listitem"><p>Make sure to include
                                an "<code class="literal">[Install]</code>"
                                section including installation
                                information for the unit file. See
                                <a href="systemd.unit.html"><span class="citerefentry"><span class="refentrytitle">systemd.unit</span>(5)</span></a>
                                for details. To activate your service
                                on boot, make sure to add a
                                <code class="varname">WantedBy=multi-user.target</code>
                                or
                                <code class="varname">WantedBy=graphical.target</code>
                                directive. To activate your socket on
                                boot, make sure to add
                                <code class="varname">WantedBy=sockets.target</code>. Usually,
                                you also want to make sure that when
                                your service is installed, your socket
                                is installed too, hence add
                                <code class="varname">Also=foo.socket</code> in
                                your service file
                                <code class="filename">foo.service</code>, for
                                a hypothetical program
                                <code class="filename">foo</code>.</p></li></ol></div></div><div class="refsect2"><a name="idm214177358624"></a><h3 id="Installing Systemd Service Files">Installing Systemd Service Files<a class="headerlink" title="Permalink to this headline" href="#Installing%20Systemd%20Service%20Files">¶</a></h3><p>At the build installation time
                        (e.g. <span class="command"><strong>make install</strong></span> during
                        package build), packages are recommended to
                        install their systemd unit files in the
                        directory returned by <span class="command"><strong>pkg-config
                        systemd
                        --variable=systemdsystemunitdir</strong></span> (for
                        system services) or <span class="command"><strong>pkg-config
                        systemd
                        --variable=systemduserunitdir</strong></span>
                        (for user services). This will make the
                        services available in the system on explicit
                        request but not activate them automatically
                        during boot. Optionally, during package
                        installation (e.g. <span class="command"><strong>rpm -i</strong></span>
                        by the administrator), symlinks should be
                        created in the systemd configuration
                        directories via the <span class="command"><strong>enable</strong></span>
                        command of the
                        <a href="systemctl.html"><span class="citerefentry"><span class="refentrytitle">systemctl</span>(1)</span></a>
                        tool to activate them automatically on
                        boot.</p><p>Packages using
                        <a href="autoconf.html"><span class="citerefentry"><span class="refentrytitle">autoconf</span>(1)</span></a>
                        are recommended to use a configure script
                        excerpt like the following to determine the
                        unit installation path during source
                        configuration:</p><pre class="programlisting">PKG_PROG_PKG_CONFIG
AC_ARG_WITH([systemdsystemunitdir],
     [AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files])],,
     [with_systemdsystemunitdir=auto])
AS_IF([test "x$with_systemdsystemunitdir" = "xyes" -o "x$with_systemdsystemunitdir" = "xauto"], [
     def_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)

     AS_IF([test "x$def_systemdsystemunitdir" = "x"],
         [AS_IF([test "x$with_systemdsystemunitdir" = "xyes"],
                [AC_MSG_ERROR([systemd support requested but pkg-config unable to query systemd package])])
          with_systemdsystemunitdir=no],
         [with_systemdsystemunitdir="$def_systemdsystemunitdir"])])
AS_IF([test "x$with_systemdsystemunitdir" != "xno"],
      [AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])])
AM_CONDITIONAL([HAVE_SYSTEMD], [test "x$with_systemdsystemunitdir" != "xno"])</pre><p>This snippet allows automatic
                        installation of the unit files on systemd
                        machines, and optionally allows their
                        installation even on machines lacking
                        systemd. (Modification of this snippet for the
                        user unit directory is left as an exercise for the
                        reader.)</p><p>Additionally, to ensure that
                        <span class="command"><strong>make distcheck</strong></span> continues to
                        work, it is recommended to add the following
                        to the top-level <code class="filename">Makefile.am</code>
                        file in
                        <a href="automake.html"><span class="citerefentry"><span class="refentrytitle">automake</span>(1)</span></a>-based
                        projects:</p><pre class="programlisting">DISTCHECK_CONFIGURE_FLAGS = \
        --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)</pre><p>Finally, unit files should be installed in the system with an automake excerpt like the following:</p><pre class="programlisting">if HAVE_SYSTEMD
systemdsystemunit_DATA = \
        foobar.socket \
        foobar.service
endif</pre><p>In the
                        <a href="rpm.html"><span class="citerefentry"><span class="refentrytitle">rpm</span>(8)</span></a>
                        <code class="filename">.spec</code> file, use snippets
                        like the following to enable/disable the
                        service during
                        installation/deinstallation. This makes use of
                        the RPM macros shipped along systemd. Consult
                        the packaging guidelines of your distribution
                        for details and the equivalent for other
                        package managers.</p><p>At the top of the file:</p><pre class="programlisting">BuildRequires: systemd
%{?systemd_requires}</pre><p>And as scriptlets, further down:</p><pre class="programlisting">%post
%systemd_post foobar.service foobar.socket

%preun
%systemd_preun foobar.service foobar.socket

%postun
%systemd_postun</pre><p>If the service shall be restarted during
                        upgrades, replace the
                        "<code class="literal">%postun</code>" scriptlet above
                        with the following:</p><pre class="programlisting">%postun
%systemd_postun_with_restart foobar.service</pre><p>Note that
                        "<code class="literal">%systemd_post</code>" and
                        "<code class="literal">%systemd_preun</code>" expect the
                        names of all units that are installed/removed
                        as arguments, separated by
                        spaces. "<code class="literal">%systemd_postun</code>"
                        expects no
                        arguments. "<code class="literal">%systemd_postun_with_restart</code>"
                        expects the units to restart as
                        arguments.</p><p>To facilitate upgrades from a package
                        version that shipped only SysV init scripts to
                        a package version that ships both a SysV init
                        script and a native systemd service file, use
                        a fragment like the following:</p><pre class="programlisting">%triggerun -- foobar &lt; 0.47.11-1
if /sbin/chkconfig --level 5 foobar ; then
        /bin/systemctl --no-reload enable foobar.service foobar.socket &gt;/dev/null 2&gt;&amp;1 || :
fi</pre><p>Where 0.47.11-1 is the first package
                        version that includes the native unit
                        file. This fragment will ensure that the first
                        time the unit file is installed, it will be
                        enabled if and only if the SysV init script is
                        enabled, thus making sure that the enable
                        status is not changed. Note that
                        <span class="command"><strong>chkconfig</strong></span> is a command
                        specific to Fedora which can be used to check
                        whether a SysV init script is enabled. Other
                        operating systems will have to use different
                        commands here.</p></div></div><div class="refsect1"><a name="idm214178311488"></a><h2 id="Porting Existing Daemons">Porting Existing Daemons<a class="headerlink" title="Permalink to this headline" href="#Porting%20Existing%20Daemons">¶</a></h2><p>Since new-style init systems such as systemd are
                compatible with traditional SysV init systems, it is
                not strictly necessary to port existing daemons to the
                new style. However, doing so offers additional
                functionality to the daemons as well as simplifying
                integration into new-style init systems.</p><p>To port an existing SysV compatible daemon, the
                following steps are recommended:</p><div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><p>If not already implemented,
                        add an optional command line switch to the
                        daemon to disable daemonization. This is
                        useful not only for using the daemon in
                        new-style init systems, but also to ease
                        debugging.</p></li><li class="listitem"><p>If the daemon offers
                        interfaces to other software running on the
                        local system via local <code class="constant">AF_UNIX</code> sockets,
                        consider implementing socket-based activation
                        (see above). Usually, a minimal patch is
                        sufficient to implement this: Extend the
                        socket creation in the daemon code so that
                        <a href="sd_listen_fds.html"><span class="citerefentry"><span class="refentrytitle">sd_listen_fds</span>(3)</span></a>
                        is checked for already passed sockets
                        first. If sockets are passed (i.e. when
                        <code class="function">sd_listen_fds()</code> returns a
                        positive value), skip the socket creation step
                        and use the passed sockets. Secondly, ensure
                        that the file system socket nodes for local
                        <code class="constant">AF_UNIX</code> sockets used in the socket-based
                        activation are not removed when the daemon
                        shuts down, if sockets have been
                        passed. Third, if the daemon normally closes
                        all remaining open file descriptors as part of
                        its initialization, the sockets passed from
                        the init system must be spared. Since
                        new-style init systems guarantee that no
                        left-over file descriptors are passed to
                        executed processes, it might be a good choice
                        to simply skip the closing of all remaining
                        open file descriptors if sockets are
                        passed.</p></li><li class="listitem"><p>Write and install a systemd
                        unit file for the service (and the sockets if
                        socket-based activation is used, as well as a
                        path unit file, if the daemon processes a
                        spool directory), see above for
                        details.</p></li><li class="listitem"><p>If the daemon exposes
                        interfaces via D-Bus, write and install a
                        D-Bus activation file for the service, see
                        above for details.</p></li></ol></div></div><div class="refsect1"><a name="idm214180581568"></a><h2 id="Placing Daemon Data">Placing Daemon Data<a class="headerlink" title="Permalink to this headline" href="#Placing%20Daemon%20Data">¶</a></h2><p>It is recommended to follow the general
                guidelines for placing package files, as discussed in
                <a href="file-hierarchy.html"><span class="citerefentry"><span class="refentrytitle">file-hierarchy</span>(7)</span></a>.</p></div><div class="refsect1"><a name="idm214180579440"></a><h2 id="See Also">See Also<a class="headerlink" title="Permalink to this headline" href="#See%20Also">¶</a></h2><p>
                        <a href="systemd.html"><span class="citerefentry"><span class="refentrytitle">systemd</span>(1)</span></a>,
                        <a href="sd-daemon.html"><span class="citerefentry"><span class="refentrytitle">sd-daemon</span>(3)</span></a>,
                        <a href="sd_listen_fds.html"><span class="citerefentry"><span class="refentrytitle">sd_listen_fds</span>(3)</span></a>,
                        <a href="sd_notify.html"><span class="citerefentry"><span class="refentrytitle">sd_notify</span>(3)</span></a>,
                        <a href="daemon.html"><span class="citerefentry"><span class="refentrytitle">daemon</span>(3)</span></a>,
                        <a href="systemd.service.html"><span class="citerefentry"><span class="refentrytitle">systemd.service</span>(5)</span></a>,
                        <a href="file-hierarchy.html"><span class="citerefentry"><span class="refentrytitle">file-hierarchy</span>(7)</span></a>
                </p></div></div></body></html>