Anatomy of a typical Unix-like/Linux daemon

25 Apr 2020 - tsp

This short blog post should provide a short introduction into the anatomy of the typical Unix or Linux daemon. It describes the typical steps taken by a daemon to demonize itself.

What is a daemon process anyways?

A daemon process is a process that doesn’t directly interact with a terminal or graphical user interface, runs in the background and provides some service. Typical examples are webservers, mail servers, chronological job schedulers (cron), your audio server (like jack, etc.), the syslog server, etc. These processes normally expose a service and one or more methods of interaction. They are of course different to batch jobs that often also run inside demonized containers.

Which steps does a daemon undertake?

Alternative flow

An alternative flow might substitute the first fork and the call to the setsid function as well as closing stdint as well as stdout and stderr pipes by calling the daemon(3) function. This function allows one to move into background, detach from the controlling terminal and optionally do a chdir into the root directory / and optionally redirection all standard input and output pipes to /dev/null. The following example won’t use that approach.

How to provide logging from inside a daemon process

There are a few different approaches one might take:

It’s a good idea to provide a way to run the process for debugging purposes in foreground (and of course also allow termination using the SIGINT signal - that’s the signal that gets transmitted when one uses CTRL+C on the controlling terminal). This allows easy debugging under many circumstances during development and manual deployment scenarios.

A basic skeleton

With all that in mind we now can develop a simple basic daemon (the code is provided as a GitHub GIST):

This article is tagged: Programming


Dipl.-Ing. Thomas Spielauer, Wien (webcomplains389t48957@tspi.at)

This webpage is also available via TOR at http://jugujbrirx3irwyx.onion/

Valid HTML 4.01 Strict Powered by FreeBSD IPv6 support