{
    "mode": "man",
    "parameter": "daemon",
    "section": "7",
    "url": "https://www.chedong.com/phpMan.php/man/daemon/7/json",
    "generated": "2026-06-15T13:11:06Z",
    "sections": {
        "NAME": {
            "content": "daemon - Writing and packaging system daemons\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "A daemon is a service process that runs in the background and supervises the system or\nprovides functionality to other processes. Traditionally, daemons are implemented following a\nscheme originating in SysV Unix. Modern daemons should follow a simpler yet more powerful\nscheme (here called \"new-style\" daemons), as implemented by systemd(1). This manual page\ncovers both schemes, and in particular includes recommendations for daemons that shall be\nincluded in the systemd init system.\n",
            "subsections": [
                {
                    "name": "SysV Daemons",
                    "content": "When a traditional SysV daemon starts, it should execute the following steps as part of the\ninitialization. Note that these steps are unnecessary for new-style daemons (see below), and\nshould only be implemented if compatibility with SysV is essential.\n\n1. Close all open file descriptors except standard input, output, and error (i.e. the first\nthree file descriptors 0, 1, 2). This ensures that no accidentally passed file descriptor\nstays around in the daemon process. On Linux, this is best implemented by iterating\nthrough /proc/self/fd, with a fallback of iterating from file descriptor 3 to the value\nreturned by getrlimit() for RLIMITNOFILE.\n\n2. Reset all signal handlers to their default. This is best done by iterating through the\navailable signals up to the limit of NSIG and resetting them to SIGDFL.\n\n3. Reset the signal mask using sigprocmask().\n\n4. Sanitize the environment block, removing or resetting environment variables that might\nnegatively impact daemon runtime.\n\n5. Call fork(), to create a background process.\n\n6. In the child, call setsid() to detach from any terminal and create an independent\nsession.\n\n7. In the child, call fork() again, to ensure that the daemon can never re-acquire a\nterminal again. (This relevant if the program — and all its dependencies — does not\ncarefully specify `ONOCTTY` on each and every single `open()` call that might\npotentially open a TTY device node.)\n\n8. Call exit() in the first child, so that only the second child (the actual daemon process)\nstays around. This ensures that the daemon process is re-parented to init/PID 1, as all\ndaemons should be.\n\n9. In the daemon process, connect /dev/null to standard input, output, and error.\n\n10. In the daemon process, reset the umask to 0, so that the file modes passed to open(),\nmkdir() and suchlike directly control the access mode of the created files and\ndirectories.\n\n11. In the daemon process, change the current directory to the root directory (/), in order\nto avoid that the daemon involuntarily blocks mount points from being unmounted.\n\n12. In the daemon process, write the daemon PID (as returned by getpid()) to a PID file, for\nexample /run/foobar.pid (for a hypothetical daemon \"foobar\") to ensure that the daemon\ncannot be started more than once. This must be implemented in race-free fashion so that\nthe PID file is only updated when it is verified at the same time that the PID previously\nstored in the PID file no longer exists or belongs to a foreign process.\n\n13. In the daemon process, drop privileges, if possible and applicable.\n\n14. From the daemon process, notify the original process started that initialization is\ncomplete. This can be implemented via an unnamed pipe or similar communication channel\nthat is created before the first fork() and hence available in both the original and the\ndaemon process.\n\n15. Call exit() in the original process. The process that invoked the daemon must be able to\nrely on that this exit() happens after initialization is complete and all external\ncommunication channels are established and accessible.\n\nThe BSD daemon() function should not be used, as it implements only a subset of these steps.\n\nA daemon that needs to provide compatibility with SysV systems should implement the scheme\npointed out above. However, it is recommended to make this behavior optional and configurable\nvia a command line argument to ease debugging as well as to simplify integration into systems\nusing systemd.\n"
                },
                {
                    "name": "New-Style Daemons",
                    "content": "Modern services for Linux should be implemented as new-style daemons. This makes it easier to\nsupervise and control them at runtime and simplifies their implementation.\n\nFor developing a new-style daemon, none of the initialization steps recommended for SysV\ndaemons need to be implemented. New-style init systems such as systemd make all of them\nredundant. Moreover, since some of these steps interfere with process monitoring, file\ndescriptor passing and other functionality of the init system, it is recommended not to\nexecute them when run as new-style service.\n\nNote that new-style init systems guarantee execution of daemon processes in a clean process\ncontext: it is guaranteed that the environment block is sanitized, that the signal handlers\nand mask is reset and that no left-over file descriptors are passed. Daemons will be executed\nin their own session, with standard input connected to /dev/null and standard output/error\nconnected to the systemd-journald.service(8) logging service, unless otherwise configured.\nThe umask is reset.\n\nIt is recommended for new-style daemons to implement the following:\n\n1. If SIGTERM is received, shut down the daemon and exit cleanly.\n\n2. If SIGHUP is received, reload the configuration files, if this applies.\n\n3. Provide a correct exit code from the main daemon process, as this is used by the init\nsystem to detect service errors and problems. It is recommended to follow the exit code\nscheme as defined in the LSB recommendations for SysV init scripts[1].\n\n4. If possible and applicable, expose the daemon's control interface via the D-Bus IPC\nsystem and grab a bus name as last step of initialization.\n\n5. For integration in systemd, provide a .service unit file that carries information about\nstarting, stopping and otherwise maintaining the daemon. See systemd.service(5) for\ndetails.\n\n6. As much as possible, rely on the init system's functionality to limit the access of the\ndaemon to files, services and other resources, i.e. in the case of systemd, rely on\nsystemd's resource limit control instead of implementing your own, rely on systemd's\nprivilege dropping code instead of implementing it in the daemon, and similar. See\nsystemd.exec(5) for the available controls.\n\n7. If D-Bus is used, make your daemon bus-activatable by supplying a D-Bus service\nactivation configuration file. This has multiple advantages: your daemon may be started\nlazily on-demand; it may be started in parallel to other daemons requiring it — which\nmaximizes parallelization and boot-up speed; your daemon can be restarted on failure\nwithout losing any bus requests, as the bus queues requests for activatable services. See\nbelow for details.\n\n8. If your daemon provides services to other local processes or remote clients via a socket,\nit should be made socket-activatable following the scheme pointed out below. Like D-Bus\nactivation, this enables on-demand starting of services as well as it allows improved\nparallelization of service start-up. Also, for state-less protocols (such as syslog,\nDNS), a daemon implementing socket-based activation can be restarted without losing a\nsingle request. See below for details.\n\n9. If applicable, a daemon should notify the init system about startup completion or status\nupdates via the sdnotify(3) interface.\n\n10. Instead of using the syslog() call to log directly to the system syslog service, a\nnew-style daemon may choose to simply log to standard error via fprintf(), which is then\nforwarded to syslog by the init system. If log levels are necessary, these can be encoded\nby prefixing individual log lines with strings like \"<4>\" (for log level 4 \"WARNING\" in\nthe syslog priority scheme), following a similar style as the Linux kernel's printk()\nlevel system. For details, see sd-daemon(3) and systemd.exec(5).\n\n11. As new-style daemons are invoked without a controlling TTY (but as their own session\nleaders) care should be taken to always specify `ONOCTTY` on `open()` calls that\npossibly reference a TTY device node, so that no controlling TTY is accidentally\nacquired.\n\nThese recommendations are similar but not identical to the Apple MacOS X Daemon\nRequirements[2].\n"
                }
            ]
        },
        "ACTIVATION": {
            "content": "New-style init systems provide multiple additional mechanisms to activate services, as\ndetailed below. It is common that services are configured to be activated via more than one\nmechanism at the same time. An example for systemd: bluetoothd.service might get activated\neither when Bluetooth hardware is plugged in, or when an application accesses its programming\ninterfaces via D-Bus. Or, a print server daemon might get activated when traffic arrives at\nan IPP port, or when a printer is plugged in, or when a file is queued in the printer spool\ndirectory. Even for services that are intended to be started on system bootup\nunconditionally, it is a good idea to implement some of the various activation schemes\noutlined below, in order to maximize parallelization. If a daemon implements a D-Bus service\nor listening socket, implementing the full bus and socket activation scheme allows starting\nof the daemon with its clients in parallel (which speeds up boot-up), since all its\ncommunication channels are established already, and no request is lost because client\nrequests will be queued by the bus system (in case of D-Bus) or the kernel (in case of\nsockets) until the activation is completed.\n",
            "subsections": [
                {
                    "name": "Activation on Boot",
                    "content": "Old-style daemons are usually activated exclusively on boot (and manually by the\nadministrator) via SysV init scripts, as detailed in the LSB Linux Standard Base Core\nSpecification[1]. This method of activation is supported ubiquitously on Linux init systems,\nboth old-style and new-style systems. Among other issues, SysV init scripts have the\ndisadvantage of involving shell scripts in the boot process. New-style init systems generally\nemploy updated versions of activation, both during boot-up and during runtime and using more\nminimal service description files.\n\nIn systemd, if the developer or administrator wants to make sure that a service or other unit\nis activated automatically on boot, it is recommended to place a symlink to the unit file in\nthe .wants/ directory of either multi-user.target or graphical.target, which are normally\nused as boot targets at system startup. See systemd.unit(5) for details about the .wants/\ndirectories, and systemd.special(7) for details about the two boot targets.\n"
                },
                {
                    "name": "Socket-Based Activation",
                    "content": "In order to maximize the possible parallelization and robustness and simplify configuration\nand development, it is recommended for all new-style daemons that communicate via listening\nsockets to employ socket-based activation. In a socket-based activation scheme, the creation\nand binding of the listening socket as primary communication channel of daemons to local (and\nsometimes remote) clients is moved out of the daemon code and into the init system. Based on\nper-daemon configuration, the init system installs the sockets and then hands them off to the\nspawned process as soon as the respective daemon is to be started. Optionally, activation of\nthe service can be delayed until the first inbound traffic arrives at the socket to implement\non-demand activation of daemons. However, the primary advantage of this scheme is that all\nproviders and all consumers of the sockets can be started in parallel as soon as all sockets\nare established. In addition to that, daemons can be restarted with losing only a minimal\nnumber of client transactions, or even any client request at all (the latter is particularly\ntrue for state-less protocols, such as DNS or syslog), because the socket stays bound and\naccessible during the restart, and all requests are queued while the daemon cannot process\nthem.\n\nNew-style daemons which support socket activation must be able to receive their sockets from\nthe init system instead of creating and binding them themselves. For details about the\nprogramming interfaces for this scheme provided by systemd, see sdlistenfds(3) and sd-\ndaemon(3). For details about porting existing daemons to socket-based activation, see below.\nWith minimal effort, it is possible to implement socket-based activation in addition to\ntraditional internal socket creation in the same codebase in order to support both new-style\nand old-style init systems from the same daemon binary.\n\nsystemd implements socket-based activation via .socket units, which are described in\nsystemd.socket(5). When configuring socket units for socket-based activation, it is essential\nthat all listening sockets are pulled in by the special target unit sockets.target. It is\nrecommended to place a WantedBy=sockets.target directive in the [Install] section to\nautomatically add such a dependency on installation of a socket unit. Unless\nDefaultDependencies=no is set, the necessary ordering dependencies are implicitly created for\nall socket units. For more information about sockets.target, see systemd.special(7). It is\nnot necessary or recommended to place any additional dependencies on socket units (for\nexample from multi-user.target or suchlike) when one is installed in sockets.target.\n"
                },
                {
                    "name": "Bus-Based Activation",
                    "content": "When the D-Bus IPC system is used for communication with clients, new-style daemons should\nemploy bus activation so that they are automatically activated when a client application\naccesses their IPC interfaces. This is configured in D-Bus service files (not to be confused\nwith systemd service unit files!). To ensure that D-Bus uses systemd to start-up and maintain\nthe daemon, use the SystemdService= directive in these service files to configure the\nmatching systemd service for a D-Bus service. e.g.: For a D-Bus service whose D-Bus\nactivation file is named org.freedesktop.RealtimeKit.service, make sure to set\nSystemdService=rtkit-daemon.service in that file to bind it to the systemd service\nrtkit-daemon.service. This is needed to make sure that the daemon is started in a race-free\nfashion when activated via multiple mechanisms simultaneously.\n"
                },
                {
                    "name": "Device-Based Activation",
                    "content": "Often, daemons that manage a particular type of hardware should be activated only when the\nhardware of the respective kind is plugged in or otherwise becomes available. In a new-style\ninit system, it is possible to bind activation to hardware plug/unplug events. In systemd,\nkernel devices appearing in the sysfs/udev device tree can be exposed as units if they are\ntagged with the string \"systemd\". Like any other kind of unit, they may then pull in other\nunits when activated (i.e. plugged in) and thus implement device-based activation. systemd\ndependencies may be encoded in the udev database via the SYSTEMDWANTS= property. See\nsystemd.device(5) for details. Often, it is nicer to pull in services from devices only\nindirectly via dedicated targets. Example: Instead of pulling in bluetoothd.service from all\nthe various bluetooth dongles and other hardware available, pull in bluetooth.target from\nthem and bluetoothd.service from that target. This provides for nicer abstraction and gives\nadministrators the option to enable bluetoothd.service via controlling a\nbluetooth.target.wants/ symlink uniformly with a command like enable of systemctl(1) instead\nof manipulating the udev ruleset.\n"
                },
                {
                    "name": "Path-Based Activation",
                    "content": "Often, runtime of daemons processing spool files or directories (such as a printing system)\ncan be delayed until these file system objects change state, or become non-empty. New-style\ninit systems provide a way to bind service activation to file system changes. systemd\nimplements this scheme via path-based activation configured in .path units, as outlined in\nsystemd.path(5).\n"
                },
                {
                    "name": "Timer-Based Activation",
                    "content": "Some daemons that implement clean-up jobs that are intended to be executed in regular\nintervals benefit from timer-based activation. In systemd, this is implemented via .timer\nunits, as described in systemd.timer(5).\n"
                },
                {
                    "name": "Other Forms of Activation",
                    "content": "Other forms of activation have been suggested and implemented in some systems. However, there\nare often simpler or better alternatives, or they can be put together of combinations of the\nschemes above. Example: Sometimes, it appears useful to start daemons or .socket units when a\nspecific IP address is configured on a network interface, because network sockets shall be\nbound to the address. However, an alternative to implement this is by utilizing the Linux\nIPFREEBIND/IPV6FREEBIND socket option, as accessible via FreeBind=yes in systemd socket\nfiles (see systemd.socket(5) for details). This option, when enabled, allows sockets to be\nbound to a non-local, not configured IP address, and hence allows bindings to a particular IP\naddress before it actually becomes available, making such an explicit dependency to the\nconfigured address redundant. Another often suggested trigger for service activation is low\nsystem load. However, here too, a more convincing approach might be to make proper use of\nfeatures of the operating system, in particular, the CPU or I/O scheduler of Linux. Instead\nof scheduling jobs from userspace based on monitoring the OS scheduler, it is advisable to\nleave the scheduling of processes to the OS scheduler itself. systemd provides fine-grained\naccess to the CPU and I/O schedulers. If a process executed by the init system shall not\nnegatively impact the amount of CPU or I/O bandwidth available to other processes, it should\nbe configured with CPUSchedulingPolicy=idle and/or IOSchedulingClass=idle. Optionally, this\nmay be combined with timer-based activation to schedule background jobs during runtime and\nwith minimal impact on the system, and remove it from the boot phase itself.\n"
                }
            ]
        },
        "INTEGRATION WITH SYSTEMD": {
            "content": "",
            "subsections": [
                {
                    "name": "Writing systemd Unit Files",
                    "content": "When writing systemd unit files, it is recommended to consider the following suggestions:\n\n1. If possible, do not use the Type=forking setting in service files. But if you do, make\nsure to set the PID file path using PIDFile=. See systemd.service(5) for details.\n\n2. If your daemon registers a D-Bus name on the bus, make sure to use Type=dbus in the\nservice file if possible.\n\n3. Make sure to set a good human-readable description string with Description=.\n\n4. Do not disable DefaultDependencies=, unless you really know what you do and your unit is\ninvolved in early boot or late system shutdown.\n\n5. Normally, little if any dependencies should need to be defined explicitly. However, if\nyou do configure explicit dependencies, only refer to unit names listed on\nsystemd.special(7) or names introduced by your own package to keep the unit file\noperating system-independent.\n\n6. Make sure to include an [Install] section including installation information for the unit\nfile. See systemd.unit(5) for details. To activate your service on boot, make sure to add\na WantedBy=multi-user.target or WantedBy=graphical.target directive. To activate your\nsocket on boot, make sure to add WantedBy=sockets.target. Usually, you also want to make\nsure that when your service is installed, your socket is installed too, hence add\nAlso=foo.socket in your service file foo.service, for a hypothetical program foo.\n"
                },
                {
                    "name": "Installing systemd Service Files",
                    "content": "At the build installation time (e.g.  make install during package build), packages are\nrecommended to install their systemd unit files in the directory returned by pkg-config\nsystemd --variable=systemdsystemunitdir (for system services) or pkg-config systemd\n--variable=systemduserunitdir (for user services). This will make the services available in\nthe system on explicit request but not activate them automatically during boot. Optionally,\nduring package installation (e.g.  rpm -i by the administrator), symlinks should be created\nin the systemd configuration directories via the enable command of the systemctl(1) tool to\nactivate them automatically on boot.\n\nPackages using autoconf(1) are recommended to use a configure script excerpt like the\nfollowing to determine the unit installation path during source configuration:\n\nPKGPROGPKGCONFIG\nACARGWITH([systemdsystemunitdir],\n[ASHELPSTRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files])],,\n[withsystemdsystemunitdir=auto])\nASIF([test \"x$withsystemdsystemunitdir\" = \"xyes\" -o \"x$withsystemdsystemunitdir\" = \"xauto\"], [\ndefsystemdsystemunitdir=$($PKGCONFIG --variable=systemdsystemunitdir systemd)\n\nASIF([test \"x$defsystemdsystemunitdir\" = \"x\"],\n[ASIF([test \"x$withsystemdsystemunitdir\" = \"xyes\"],\n[ACMSGERROR([systemd support requested but pkg-config unable to query systemd package])])\nwithsystemdsystemunitdir=no],\n[withsystemdsystemunitdir=\"$defsystemdsystemunitdir\"])])\nASIF([test \"x$withsystemdsystemunitdir\" != \"xno\"],\n[ACSUBST([systemdsystemunitdir], [$withsystemdsystemunitdir])])\nAMCONDITIONAL([HAVESYSTEMD], [test \"x$withsystemdsystemunitdir\" != \"xno\"])\n\nThis snippet allows automatic installation of the unit files on systemd machines, and\noptionally allows their installation even on machines lacking systemd. (Modification of this\nsnippet for the user unit directory is left as an exercise for the reader.)\n\nAdditionally, to ensure that make distcheck continues to work, it is recommended to add the\nfollowing to the top-level Makefile.am file in automake(1)-based projects:\n\nAMDISTCHECKCONFIGUREFLAGS = \\\n--with-systemdsystemunitdir=$$dcinstallbase/$(systemdsystemunitdir)\n\nFinally, unit files should be installed in the system with an automake excerpt like the\nfollowing:\n\nif HAVESYSTEMD\nsystemdsystemunitDATA = \\\nfoobar.socket \\\nfoobar.service\nendif\n\nIn the rpm(8) .spec file, use snippets like the following to enable/disable the service\nduring installation/deinstallation. This makes use of the RPM macros shipped along systemd.\nConsult the packaging guidelines of your distribution for details and the equivalent for\nother package managers.\n\nAt the top of the file:\n\nBuildRequires: systemd\n%{?systemdrequires}\n\nAnd as scriptlets, further down:\n\n%post\n%systemdpost foobar.service foobar.socket\n\n%preun\n%systemdpreun foobar.service foobar.socket\n\n%postun\n%systemdpostun\n\nIf the service shall be restarted during upgrades, replace the \"%postun\" scriptlet above with\nthe following:\n\n%postun\n%systemdpostunwithrestart foobar.service\n\nNote that \"%systemdpost\" and \"%systemdpreun\" expect the names of all units that are\ninstalled/removed as arguments, separated by spaces.  \"%systemdpostun\" expects no arguments.\n\"%systemdpostunwithrestart\" expects the units to restart as arguments.\n\nTo facilitate upgrades from a package version that shipped only SysV init scripts to a\npackage version that ships both a SysV init script and a native systemd service file, use a\nfragment like the following:\n\n%triggerun -- foobar < 0.47.11-1\nif /sbin/chkconfig --level 5 foobar ; then\n/bin/systemctl --no-reload enable foobar.service foobar.socket >/dev/null 2>&1 || :\nfi\n\nWhere 0.47.11-1 is the first package version that includes the native unit file. This\nfragment will ensure that the first time the unit file is installed, it will be enabled if\nand only if the SysV init script is enabled, thus making sure that the enable status is not\nchanged. Note that chkconfig is a command specific to Fedora which can be used to check\nwhether a SysV init script is enabled. Other operating systems will have to use different\ncommands here.\n"
                }
            ]
        },
        "PORTING EXISTING DAEMONS": {
            "content": "Since new-style init systems such as systemd are compatible with traditional SysV init\nsystems, it is not strictly necessary to port existing daemons to the new style. However,\ndoing so offers additional functionality to the daemons as well as simplifying integration\ninto new-style init systems.\n\nTo port an existing SysV compatible daemon, the following steps are recommended:\n\n1. If not already implemented, add an optional command line switch to the daemon to disable\ndaemonization. This is useful not only for using the daemon in new-style init systems,\nbut also to ease debugging.\n\n2. If the daemon offers interfaces to other software running on the local system via local\nAFUNIX sockets, consider implementing socket-based activation (see above). Usually, a\nminimal patch is sufficient to implement this: Extend the socket creation in the daemon\ncode so that sdlistenfds(3) is checked for already passed sockets first. If sockets are\npassed (i.e. when sdlistenfds() returns a positive value), skip the socket creation\nstep and use the passed sockets. Secondly, ensure that the file system socket nodes for\nlocal AFUNIX sockets used in the socket-based activation are not removed when the daemon\nshuts down, if sockets have been passed. Third, if the daemon normally closes all\nremaining open file descriptors as part of its initialization, the sockets passed from\nthe init system must be spared. Since new-style init systems guarantee that no left-over\nfile descriptors are passed to executed processes, it might be a good choice to simply\nskip the closing of all remaining open file descriptors if sockets are passed.\n\n3. Write and install a systemd unit file for the service (and the sockets if socket-based\nactivation is used, as well as a path unit file, if the daemon processes a spool\ndirectory), see above for details.\n\n4. If the daemon exposes interfaces via D-Bus, write and install a D-Bus activation file for\nthe service, see above for details.\n",
            "subsections": []
        },
        "PLACING DAEMON DATA": {
            "content": "It is recommended to follow the general guidelines for placing package files, as discussed in\nfile-hierarchy(7).\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "systemd(1), sd-daemon(3), sdlistenfds(3), sdnotify(3), daemon(3), systemd.service(5),\nfile-hierarchy(7)\n",
            "subsections": []
        },
        "NOTES": {
            "content": "1. LSB recommendations for SysV init scripts\nhttp://refspecs.linuxbase.org/LSB3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html\n\n2. Apple MacOS X Daemon Requirements\nhttps://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html\n\n\n\nsystemd 249                                                                                DAEMON(7)",
            "subsections": []
        }
    },
    "summary": "daemon - Writing and packaging system daemons",
    "flags": [],
    "examples": [],
    "see_also": [
        {
            "name": "systemd",
            "section": "1",
            "url": "https://www.chedong.com/phpMan.php/man/systemd/1/json"
        },
        {
            "name": "sd-daemon",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/sd-daemon/3/json"
        },
        {
            "name": "sdlistenfds",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/sdlistenfds/3/json"
        },
        {
            "name": "sdnotify",
            "section": "3",
            "url": "https://www.chedong.com/phpMan.php/man/sdnotify/3/json"
        },
        {
            "name": "systemd.service",
            "section": "5",
            "url": "https://www.chedong.com/phpMan.php/man/systemd.service/5/json"
        },
        {
            "name": "file-hierarchy",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/file-hierarchy/7/json"
        }
    ]
}