man 7 daemon
describes how to create daemon in great detail. My answer is just excerpt from this manual.
There are at least two types of daemons:
If you are interested in traditional SysV daemon, you should implement the following steps:
- 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
/proc/self/fd
, with a fallback of iterating from file descriptor 3 to the value returned bygetrlimit()
forRLIMIT_NOFILE
.- 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 toSIG_DFL
.- Reset the signal mask using
sigprocmask()
.- Sanitize the environment block, removing or resetting environment variables that might negatively impact daemon runtime.
- Call
fork()
, to create a background process.- In the child, call
setsid()
to detach from any terminal and create an independent session.- In the child, call
fork()
again, to ensure that the daemon can never re-acquire a terminal again.- Call
exit()
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.- In the daemon process, connect
/dev/null
to standard input, output, and error.- 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.- 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.- 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 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.- In the daemon process, drop privileges, if possible and applicable.
- 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
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 that thisexit()
happens after initialization is complete and all external communication channels are established and accessible.
Note this warning:
The BSD
daemon()
function should not be used, as it implements only a subset of these steps.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.
Note that daemon()
is not POSIX compliant.
For new-style daemons the following steps are recommended:
- If
SIGTERM
is received, shut down the daemon and exit cleanly.- If
SIGHUP
is received, reload the configuration files, if this applies.- 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 LSB recommendations for SysV init scripts.
- 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.
- For integration in systemd, provide a .service unit file that carries information about starting, stopping and otherwise maintaining the daemon. See
systemd.service(5)
for details.- 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
systemd.exec(5)
for the available controls.- 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 applicable, a daemon should notify the init system about startup completion or status updates via the
sd_notify(3)
interface.- 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 by the init system. 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)
.
To learn more read whole man 7 daemon
.