DAEMON(7)
๐ฆ daemon(7) โ the manual page ๐
okay bestie, welcome to daemon(7) โ the one where we talk about writing and packaging system daemons. this is the whole vibe guide. no cap. ๐ธ
โจ NAME โจ
daemon โ writing and packaging system daemons ๐
๐ DESCRIPTION ๐
so a daemon is a service process that justโฆ lives in the background? like it's running the whole time, supervising the system or handing functionality to other processes. very main character, very "i'm not in the foreground but everything depends on me" energy. ๐ซถ
traditionally, daemons were built following a scheme that originated in SysV Unix. but modern daemons should follow a simpler โ yet honestly more powerful โ scheme, which we call "new-style" daemons here, as implemented by systemd(1). ๐ข
this page covers both schemes, and specifically it's got recommendations for daemons that are gonna be included in the systemd init system. iykyk.
๐ SysV Daemons ๐
when a traditional SysV daemon starts up, it should do the following steps as part of its initialization. lowkey important note first: these steps are unnecessary for new-style daemons (see below!), and you should only implement them if compatibility with SysV is essential. periodt.
- close all open file descriptors except standard input, output, and error โ that's the first three file descriptors
0,1,2. this makes sure no accidentally-passed file descriptor just hangs around in the daemon process like a random ex. on Linux, the best way to do this is iterating through/proc/self/fd, with a fallback of iterating from file descriptor3up to the value returned bygetrlimit()forRLIMIT_NOFILE. ๐ - reset all signal handlers to their default. best done by iterating through the available signals up to the limit of
_NSIGand resetting them toSIG_DFL. clean slate, we love that. โจ - reset the signal mask using
sigprocmask(). ๐งน - sanitize the environment block โ remove or reset environment variables that might negatively impact daemon runtime. not everything in there deserves a seat at the table. ๐
- call
fork()to create a background process. bye bestie ๐ - in the child, call
setsid()to detach from any terminal and create an independent session. independent session = independent queen. ๐ - in the child, call
fork()again, to make sure the daemon can never re-acquire a terminal again. (this matters if the program โ and all its dependencies โ does not carefully specifyO_NOCTTYon each and every singleopen()call that might potentially open a TTY device node. emphasis on each and every single one. ๐ญ) - call
exit()in the first child, so that only the second child (the actual daemon process) stays around. this ensures the daemon process is re-parented to init/PID 1, as all daemons should be. that's just how it goes fr fr. ๐ - in the daemon process, connect
/dev/nullto standard input, output, and error. nothing to see here, literally. ๐ณ๏ธ - in the daemon process, reset the umask to
0, so that the file modes passed toopen(),mkdir()and suchlike directly control the access mode of the created files and directories. full control, no surprises. ๐ - in the daemon process, change the current directory to the root directory (
/), so the daemon doesn't involuntarily block mount points from being unmounted. rude behavior, we're not doing it. ๐ซ - in the daemon process, write the daemon PID (as returned by
getpid()) to a PID file, for example/run/foobar.pid(for a hypothetical daemon "foobar"), to ensure the daemon cannot be started more than once. > this one has a hard requirement: it 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. no shortcuts, bestie. ๐ฅ - in the daemon process, drop privileges, if possible and applicable. know your limits and thenโฆ lower them. ๐
- from the daemon process, notify the original process that started it that initialization is complete. this can be done via an unnamed pipe or a similar communication channel that is created before the first
fork()and hence available in both the original and the daemon process. ๐ฌ - call
exit()in the original process. the process that invoked the daemon must be able to rely on the fact that thisexit()happens after initialization is complete and all external communication channels are established and accessible. no lying about being ready. โญ
also: the BSD daemon() function should not be used, as it implements only a subset of these steps. so close but so not it. ๐
a daemon that needs to provide compatibility with SysV systems should implement the scheme pointed out above. however โ and this is the good advice โ it's 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. flexibility is the moment. ๐ฆ
๐ New-Style Daemons ๐
modern services for Linux should be implemented as new-style daemons. this makes it easier to supervise and control them at runtime and it simplifies their implementation. it's giving "less code, more power". โจ
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 service manager, it's recommended not to execute them when running as a new-style service. ๐ซ
heads up: new-style init systems guarantee execution of daemon processes in a clean process context. it's guaranteed that the environment block is sanitized, that the signal handlers and mask are reset, and that no left-over file descriptors are passed. daemons will be executed in their own session, with standard input connected to/dev/nulland standard output/error connected to thesystemd-journald.service(8)logging service โ unless otherwise configured. the umask is reset. so yeah, they did the homework for you. ๐
it's recommended for new-style daemons to implement the following:
- if applicable, the daemon should notify the service manager about startup completion or status updates via the
sd_notify(3)interface โ in particularREADY=1andSTATUS=.... ๐ฃ - if
SIGTERMis received, shut down the daemon and exit cleanly. aSTOPPING=1notification should be sent viasd_notify(3). graceful exit is a vibe. ๐ซถ - if
SIGHUPis received, reload the configuration files, if this applies. this should be combined with notifications viasd_notify(3):RELOADING=1andREADY=1. ๐ - provide a correct exit code from the main daemon process, because the service manager uses it to detect service errors and problems. it's recommended to follow the exit code scheme as defined in the LSB recommendations for SysV init scripts[1]. numbers don't lie. ๐ข
- if possible and applicable, expose the daemon's control interface via the D-Bus IPC system and grab a bus name as the last step of initialization. last step, bestie, we mean it. ๐
- for integration in systemd, provide a
.serviceunit file that carries information about starting, stopping and otherwise maintaining the daemon. seesystemd.service(5)for details. ๐ - as much as possible, rely on the service manager'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 so on. see
systemd.exec(5)for the available controls. don't rebuild what already slays. ๐ - 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. ๐ฅ
- 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. ๐ง
- if the service opens sockets or other files on its own, and those file descriptors shall survive a restart, the daemon should store them in the service manager via
sd_notify(3)withFDSTORE=1. keep your fds safe, bestie. ๐ - instead of using the
syslog()call to log directly to the system syslog service, a new-style daemon may choose to simply log to standard error viafprintf(), which is then forwarded to syslog. if log levels are necessary, these can be encoded by prefixing individual log lines with strings like"<4>"(for log level 4 "WARNING" in the syslog priority scheme), following a similar style as the Linux kernel'sprintk()level system. for details, seesd-daemon(3)andsystemd.exec(5). ๐ - as new-style daemons are invoked without a controlling TTY (but as their own session leaders), care should be taken to always specify
O_NOCTTYonopen(2)calls that possibly reference a TTY device node, so that no controlling TTY is accidentally acquired. accidental TTY acquisition is not the plot twist we want. ๐ญ
these recommendations are similar but not identical to the Apple MacOS X Daemon Requirements[2]. ๐ธ
๐ ACTIVATION โจ
Okay bestie, so new-style init systems don't just start stuff one way โ they've got a whole multiple additional mechanisms situation for activating services, and I'm about to walk you through every single one. ๐
And here's the vibe: it's super common that services get configured to be activated via more than one mechanism at the same time. Like, no big deal, just living that multi-activation life. ๐ธ
Example time, for systemd: bluetoothd.service might get activated either when Bluetooth hardware is plugged in, or when an application accesses its programming interfaces via D-Bus. See? Two whole routes. Or check it โ 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. Three routes, she contains multitudes. ๐
And even for services that are meant to be started on system bootup unconditionally, it's genuinely a good idea to implement some of the various activation schemes outlined below, because it maximizes parallelization. If a daemon implements a D-Bus service or listening socket, implementing the full bus and socket activation scheme lets the daemon start up with its clients in parallel (which speeds up boot-up ๐), since all its communication channels are already established โ and no request gets 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. Nothing dropped, everything queued. Iconic behavior, honestly.
๐ Activation on Boot
Old-style daemons are usually activated exclusively on boot (and manually by the administrator) via SysV init scripts, as detailed in the LSB Linux Standard Base Core Specification[1].
โ ๏ธ But here's the tea: among other issues, SysV init scripts have the disadvantage of involving shell scripts in the boot process. Support for init scripts has been phased out in modern Linux init systems, and should not be relied upon. Do not build your whole personality on init scripts, bestie. ๐ญ
New-style init systems generally use updated versions of activation โ both during boot-up and during runtime โ and they do it using more minimal service description files. Cleaner. Lighter. Slay. โจ
In systemd, if the developer or administrator wants to make sure that a service or other unit is activated automatically on boot, it's recommended to place a symlink to the unit file in the .wants/ directory of either multi-user.target or graphical.target โ which are normally used as boot targets at system startup. See systemd.unit(5) for details about the .wants/ directories, and systemd.special(7) for details about the two boot targets. ๐ฆ
๐ง Socket-Based Activation
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 use socket-based activation. ๐ซถ
So what's the scheme, exactly? 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 service manager. Based on per-daemon configuration, the service manager 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, which implements on-demand activation of daemons. Cute, right?
But the primary advantage of this scheme? All providers and all consumers of the sockets can be started in parallel as soon as all sockets are established. And on top of that, daemons can be restarted 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. The queue never stops, the daemon just takes a lil nap. ๐
New-style daemons which support socket activation must be able to receive their sockets from the service manager instead of creating and binding them themselves. For details about the programming interfaces for this scheme provided by systemd, see sd_listen_fds(3) and sd-daemon(3). For details about porting existing daemons to socket-based activation, see below. ๐
And here's the bestie-coded part: with minimal effort, it's possible to implement socket-based activation in addition to traditional internal socket creation in the same codebase, so you can support both new-style and old-style init systems from the same daemon binary. One binary, two worlds, zero drama. ๐
systemd implements socket-based activation via .socket units, which are described in systemd.socket(5). When configuring socket units for socket-based activation, it is essential that all listening sockets are pulled in by the special target unit sockets.target. It is recommended to place a WantedBy=sockets.target directive in the [Install] section to automatically add such a dependency on installation of a socket unit. Unless DefaultDependencies=no is set, the necessary ordering dependencies are implicitly created for all socket units. For more information about sockets.target, see systemd.special(7).
๐ซ It is not necessary or recommended to place any additional dependencies on socket units (for example frommulti-user.targetor suchlike) when one is installed insockets.target. Don't over-attach, it's giving clingy.
๐ธ Bus-Based Activation
When the D-Bus IPC system is used for communication with clients, new-style daemons should use bus activation so that they're automatically activated when a client application accesses their IPC interfaces. โจ
This is configured in D-Bus service files โ and not to be confused with systemd service unit files, bestie, they are different things and mixing them up is a whole situation. ๐
To ensure that D-Bus uses systemd to start-up and maintain the daemon, use the SystemdService= 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 org.freedesktop.RealtimeKit.service, make sure to set SystemdService=rtkit-daemon.service in that file to bind it to the systemd service rtkit-daemon.service.
Why do we care? Because this is needed to make sure that the daemon is started in a race-free fashion when activated via multiple mechanisms simultaneously. No races, no chaos, just vibes. ๐
๐ฅ Device-Based Activation
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's 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 "systemd". 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 SYSTEMD_WANTS= property. See systemd.device(5) for details. ๐
Often, it's nicer to pull in services from devices only indirectly via dedicated targets. Example: Instead of pulling in bluetoothd.service from all the various bluetooth dongles and other hardware available, pull in bluetooth.target from them and bluetoothd.service from that target. ๐ฆ
This provides for nicer abstraction and gives administrators the option to enable bluetoothd.service via controlling a bluetooth.target.wants/ symlink uniformly with a command like enable of systemctl(1) โ instead of manipulating the udev ruleset. So much cleaner, I'm obsessed. ๐
โญ Path-Based Activation
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 .path units, as outlined in systemd.path(5). ๐
๐ Timer-Based Activation
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 .timer units, as described in systemd.timer(5). โฐ
๐ Other Forms of Activation
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. Let's get into the receipts: ๐งพ
Example: Sometimes, it appears useful to start daemons or .socket 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/IPV6_FREEBIND socket option, as accessible via FreeBind=yes in systemd socket files (see systemd.socket(5) 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. No waiting, no dependency, just bind. โจ
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 I/O 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. Let the OS cook. ๐
systemd provides fine-grained access to the CPU and I/O schedulers. If a process executed by the service manager shall not negatively impact the amount of CPU or I/O bandwidth available to other processes, it should be configured with CPUSchedulingPolicy=idle and/or IOSchedulingClass=idle. 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. Background tasks staying in their lane, fr fr. ๐
๐ธ INTEGRATION WITH SYSTEMD ๐ธ
okay so this is the part where your lil daemon gets to live its best life inside systemd ๐ here's how to play nice with it.
โจ Writing systemd Unit Files โจ
bestie, when you're writing systemd unit files, pls consider these lil suggestions, they're not random, they're the vibe:
- if u can, do NOT use the
Type=forkingsetting in service files. but if you do (no judgement ๐ซถ), make sure you set the PID file path withPIDFile=. details live insystemd.service(5). - if your daemon registers a D-Bus name on the bus, make sure you use
Type=dbusin the service file if possible. slay. - make sure you set a good human-readable description string with
Description=. like, give it a cute lil bio. - do not disable
DefaultDependencies=, unless you really know what you're doing and your unit is involved in early boot or late system shutdown. this is not the place to be chaotic ๐ - 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
systemd.special(7)or names introduced by your own package, so the unit file stays operating system-independent. - make sure to include an
[Install]section including installation information for the unit file. seesystemd.unit(5)for details. to activate your service on boot, make sure to add aWantedBy=multi-user.targetorWantedBy=graphical.targetdirective. to activate your socket on boot, make sure to addWantedBy=sockets.target. usually, you also want to make sure that when your service is installed, your socket is installed too, hence addAlso=foo.socketin your service filefoo.service, for a hypothetical programfoo. โจ
๐ Installing systemd Service Files ๐
at build installation time (like make install during package build), packages are recommended to install their systemd unit files in the directory returned by pkg-config systemd --variable=systemdsystemunitdir (for system services) or pkg-config systemd --variable=systemduserunitdir (for user services). this makes the services available in the system on explicit request but does not activate them automatically during boot. optionally, during package installation (like rpm -i by the administrator), symlinks should be created in the systemd configuration directories via the enable command of the systemctl(1) tool to activate them automatically on boot. ๐ฆ
packages using autoconf(1) are recommended to use a configure script excerpt like the following to determine the unit installation path during source configuration:
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"])
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 ๐ you got this tho.)
additionally, to make sure make distcheck keeps working, it's recommended to add the following to the top-level Makefile.am file in automake(1)-based projects:
AM_DISTCHECK_CONFIGURE_FLAGS = \
--with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)
finally, unit files should be installed in the system with an automake excerpt like the following:
if HAVE_SYSTEMD
systemdsystemunit_DATA = \
foobar.socket \
foobar.service
endif
in the rpm(8) .spec 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. ๐
at the top of the file:
BuildRequires: systemd
%{?systemd_requires}
and as scriptlets, further down:
%post
%systemd_post foobar.service foobar.socket
%preun
%systemd_preun foobar.service foobar.socket
%postun
%systemd_postun
if the service shall be restarted during upgrades, replace the "%postun" scriptlet above with the following:
%postun
%systemd_postun_with_restart foobar.service
note that"%systemd_post"and"%systemd_preun"expect the names of all units that are installed/removed as arguments, separated by spaces."%systemd_postun"expects no arguments."%systemd_postun_with_restart"expects the units to restart as arguments. no cap, that's the whole contract.
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:
%triggerun -- foobar < 0.47.11-1
if /sbin/chkconfig --level 5 foobar ; then
/bin/systemctl --no-reload enable foobar.service foobar.socket >/dev/null 2>&1 || :
fi
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 chkconfig 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. ๐
๐ฆ PORTING EXISTING DAEMONS ๐ฆ
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. so like, it's optional but it's giving upgrade ๐
to port an existing SysV compatible daemon, the following steps are recommended:
- 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. two birds, one iconic stone ๐
- if the daemon offers interfaces to other software running on the local system via local
AF_UNIXsockets, 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 thatsd_listen_fds(3)is checked for already passed sockets first. if sockets are passed (i.e. whensd_listen_fds()returns a positive value), skip the socket creation step and use the passed sockets. secondly, ensure that the file system socket nodes for localAF_UNIXsockets 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 service manager 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. ๐ญ it's a lot but u got this fr fr - 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. โจ
- if the daemon exposes interfaces via D-Bus, write and install a D-Bus activation file for the service, see above for details. ๐
๐ธ PLACING DAEMON DATA ๐ธ
it's recommended to follow the general guidelines for placing package files, as discussed in file-hierarchy(7). short and sweet, main character energy.
๐ NOTES ๐
all example codes in this page are licensed under "MIT No Attribution" (SPDX-License-Identifier: MIT-0). go wild bestie, no attribution needed, that's the whole point of the name ๐
๐ SEE ALSO ๐
systemd(1), sd-daemon(3), sd_listen_fds(3), sd_notify(3), daemon(3), systemd.service(5), file-hierarchy(7)
๐ NOTES ๐
- LSB recommendations for SysV init scripts
http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html - Apple MacOS X Daemon Requirements
https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
and that's the whole page, we did it ๐ฅน๐ this one came out of systemd 262.1, dated with the DAEMON(7) header, so shoutout to that version and its lil timestamp for holding it down. periodt. โจ๐ซถ๐ธ
๐ฆ where this page comes from
- arch rolling: systemd 262.1-1 ยท LGPL-2.1-or-later AND CC0-1.0 AND GPL-2.0-or-later AND MIT-0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms