Skip to content
Visual explainer 2h 30m to learn 4 steps

Classic daemonization

Explain each step of the traditional double-fork daemon recipe.

By Invicly Tech, , in Linux System Programming. About 13 minutes to read.

Topic 38 of 42

In short

A daemon is a background process with no controlling terminal, such as sshd or cron. The traditional SysV recipe detaches by forking twice, starting a new session, resetting the umask and working directory and redirecting the standard streams. Under systemd most of this is unnecessary, but you will still meet it in older code.

Explained simply

A daemon is a program that runs in the background, without a window or terminal, often from boot to shutdown. sshd waits for SSH logins, cron runs scheduled jobs, and a database server waits for queries.

Before systemd, a program had to make itself a daemon. It had to cut every tie to the terminal that started it, so that closing that terminal or pressing Ctrl+C there would not kill it, and so the shell prompt would come back at once.

The classic recipe does this in a fixed set of steps: fork, start a new session, fork again, move to the root folder, set the file permission mask, point the standard input and output at /dev/null, write a PID file and send logs to syslog. Each step fixes one specific problem.

New programs usually let systemd do all of this. But you will still meet the recipe in older code and in interviews, and knowing why each step exists teaches a lot about sessions, terminals and file descriptors.

Press Play on a diagram to walk through it one step at a time.

FlowClassic double-fork daemon
  1. 1
    fork, parent exits

    Child is not a group leader; the shell returns.

  2. 2
    setsid

    New session with no controlling terminal.

  3. 3
    fork again, parent exits

    Not a session leader, so it can never gain a terminal.

  4. 4
    Reset umask and chdir to /

    Control file modes and avoid pinning mounts.

  5. 5
    Redirect fds 0, 1 and 2

    Point them at /dev/null or a log.

  6. 6
    PID file and syslog

    Let scripts find it; log without a terminal.

CompareClassic daemon vs systemd service
Classic SysV daemon
  • Forks itself into the background
  • Writes its own PID file
  • Logs through syslog
  • Init script starts and stops it
systemd service
  • Runs in the foreground
  • systemd tracks it in a cgroup
  • Logs to stdout and stderr
  • Unit file handles restart and sandboxing

In depth

Why fork, setsid, and fork again

The first fork does two jobs. The parent exits, so the shell sees the command finish and shows its prompt again. And the child, with a fresh PID, is guaranteed not to be a process group leader. That matters because setsid fails with EPERM when called by a group leader, and a program started from a shell usually is one.

setsid creates a new session and a new process group, with the child as leader of both, and with no controlling terminal. Now a hangup on the old terminal, or Ctrl+C there, cannot reach it.

The second fork is a safety net. On Linux and System V-style systems, a session leader that opens a terminal device without O_NOCTTY gets that terminal as its controlling terminal again. After the second fork the remaining process is not the session leader, so this can never happen. glibc's daemon(3) helper skips this second fork, which is why some projects write the steps themselves.

SequenceWho exits and who stays
Shell
Original process
Child
Daemon
  1. 1start ./mydaemon
    Shell to Original process: start ./mydaemon
  2. 2fork
    Original process to Child: fork
  3. 3exit: shell prompt returns
    Original process to Shell: exit: shell prompt returns
  4. 4setsid: new session, no terminal
    Child to Child: setsid: new session, no terminal
  5. 5fork again
    Child to Daemon: fork again
  6. 6exit: daemon is not session leader
    Child to Child: exit: daemon is not session leader
  7. 7umask, chdir, fds, PID file, run
    Daemon to Daemon: umask, chdir, fds, PID file, run

Working directory and umask

A process keeps its current directory in use. If the daemon was started from /mnt/usb and stays there, nobody can unmount /mnt/usb for as long as it runs. chdir("/") solves this, since the root filesystem is never unmounted while the system is up. A daemon that needs a data directory should change into that instead and use relative paths from there.

The umask is inherited from whoever started the program, so files the daemon creates would get unpredictable permissions: a user with umask 077 starts it and its log file is unreadable by the admin group; a user with umask 000 starts it and its files are world-writable. Old recipes call umask(0) and then pass explicit modes to every open. Setting a known mask such as umask(027) is safer, because it also covers files created by libraries.

  • chdir("/") so no mount point stays busy
  • umask(027): new files 640, new dirs 750
  • Always check the result of chdir

Closing and reopening descriptors

A daemon inherits every open descriptor from its parent: perhaps a socket, a log file or the write end of a pipe that some script is waiting on. Left open, they keep resources busy and can stop a parent pipeline from ever seeing end of file. So close everything above 2. On Linux 5.9 and newer, with glibc 2.34 or later, close_range(3, ~0U, 0) does it in one call. On older systems, loop up to sysconf(_SC_OPEN_MAX) or walk /proc/self/fd.

Descriptors 0, 1 and 2 need a different treatment: do not just close them, reopen them on /dev/null. If fd 1 were simply closed, the next open in the program (say the database file) would get number 1, and any stray printf would write into your database. Opening /dev/null and dup2-ing it onto 0, 1 and 2 keeps those numbers safely occupied.

  • close_range(3, ~0U, 0) closes all inherited extras
  • dup2 /dev/null onto 0, 1, 2; never leave them closed
  • Open new files with O_CLOEXEC so children do not inherit them

PID files done right

A PID file, traditionally /run/name.pid, holds the daemon's process ID so scripts can send it signals. The naive version just writes the number. It breaks in two ways: two copies started together both write the file, and after a crash the old file remains, possibly holding a PID that now belongs to some unrelated process. A script that blindly runs kill $(cat file) may hit the wrong program.

The robust version uses a lock. Open the file with O_CREAT, take an exclusive non-blocking lock (flock with LOCK_EX | LOCK_NB, or fcntl F_SETLK), and only then truncate it and write your PID. Keep the descriptor open for the whole life of the process. A second copy fails to get the lock and exits with "already running". When the process dies, even by SIGKILL, the kernel releases the lock, so a stale file is harmless. Take the lock after the final fork, so the PID you write is the daemon's own.

Logging with syslog

A daemon has no terminal, so stderr goes nowhere. The traditional answer is syslog. Call openlog("mydaemon", LOG_PID | LOG_NDELAY, LOG_DAEMON) once: the ident appears in each line, LOG_PID adds the PID, LOG_NDELAY opens the connection right away, and LOG_DAEMON is the facility (the category for routing). Then call syslog(LOG_ERR, "cannot open %s: %m", path). The %m is replaced by strerror(errno), a handy syslog extension.

Pick levels with care: LOG_ERR for failures, LOG_WARNING for odd but survivable things, LOG_INFO for normal events, LOG_DEBUG for detail. Never pass text from outside as the format string; write syslog(LOG_INFO, "%s", msg), or a % in the message becomes a format-string bug.

On systemd machines, syslog messages go through /dev/log to journald, so journalctl -t mydaemon shows them, and rsyslog may also write them to /var/log/syslog or /var/log/messages.

  • %m in a syslog format prints strerror(errno)
  • syslog(LOG_INFO, "%s", text) for untrusted text
  • logger -t test hello sends a test message from the shell

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Fork and call setsid~40m
  2. 2
    Fork again and change directory~40m
  3. 3
    Reset umask and close descriptors~40m
  4. 4
    Write a PID file and log to syslog~40m

Key points

  • setsid fails in a process group leader, which is why the first fork comes before it.
  • The second fork ensures the daemon is not a session leader and cannot acquire a terminal.
  • Close inherited descriptors and reopen 0, 1 and 2 on /dev/null.
  • daemon(3) wraps the basic steps, and systemd makes them unnecessary for new services.

Key terms

Tap a card to flip it. 0/5 known

Examples

c
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <syslog.h>
#include <unistd.h>
int main(void) {
  if (fork() > 0) exit(0);
  setsid();
  if (fork() > 0) exit(0);
  umask(027); chdir("/");
  int fd = open("/dev/null", O_RDWR);
  dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fd > 2) close(fd);
  openlog("mydaemon", LOG_PID, LOG_DAEMON);
  for (;;) { syslog(LOG_INFO, "still alive"); sleep(60); }
}

The SysV recipe; error checks omitted for brevity.

A daemonize() with error checks

The explainer's recipe skips error checks; here is one that reports failure. Step 1: the first fork, where the parent leaves with _exit so it does not flush stdio buffers twice. Step 2: setsid. Step 3: the second fork. Step 4: a known umask and the root directory. Step 5: close extra descriptors and put /dev/null on 0, 1 and 2. Errors before step 5 can still be printed with perror, because stderr is still connected. Call it before creating threads.

c
#define _GNU_SOURCE
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int daemonize(void) {
  pid_t pid = fork(); if (pid < 0) return -1;
  if (pid > 0) _exit(0);                       /* original process: shell returns */
  if (setsid() < 0) return -1;
  if ((pid = fork()) < 0) return -1;
  if (pid > 0) _exit(0);                       /* session leader leaves */
  umask(027); if (chdir("/") < 0) return -1;
  close_range(3, ~0U, 0);                      /* Linux 5.9+, glibc 2.34+ */
  int fd = open("/dev/null", O_RDWR);
  if (fd < 0 || dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0) return -1;
  if (fd > 2) close(fd);
  return 0;
}

A PID file with a lock, for a single instance

We want exactly one copy running and a PID file that is never misleading. Step 1: open or create the file, with O_CLOEXEC so children do not inherit it. Step 2: try an exclusive lock without waiting; failure with EWOULDBLOCK means another copy holds it. Step 3: only now truncate and write our PID. Step 4: return the descriptor and keep it open forever; the lock lasts as long as it is open, and the kernel drops it if we crash. Check it from a shell with flock -n /run/mydaemon.pid true, which fails while the daemon runs.

c
#include <fcntl.h>
#include <stdio.h>
#include <sys/file.h>
#include <unistd.h>
int write_pidfile(const char *path) {          /* returns fd to keep open, or -1 */
  int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644);
  if (fd < 0) return -1;
  if (flock(fd, LOCK_EX | LOCK_NB) < 0) { close(fd); return -1; }   /* already running */
  char buf[32]; int n = snprintf(buf, sizeof buf, "%ld\n", (long)getpid());
  if (ftruncate(fd, 0) < 0 || write(fd, buf, n) != n) { close(fd); return -1; }
  return fd;
}

Quick reference

  • Order: fork, setsid, fork, umask, chdir("/"), close fds, /dev/null on 0-2
  • setsid fails with EPERM in a process group leader, hence the first fork
  • ps -o pid,ppid,pgid,sid,tty,cmd -p PID: a daemon shows ? under TTY
  • close_range(3, ~0U, 0) closes every inherited descriptor above 2
  • PID file: open, flock(LOCK_EX | LOCK_NB), then write; keep the fd open
  • openlog("name", LOG_PID, LOG_DAEMON); syslog(LOG_ERR, "... %m");
  • journalctl -t name shows syslog messages from that ident
  • glibc daemon(0, 0) forks once and calls setsid; it does not fork twice

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why does the classic recipe fork before calling setsid?

Question 2

2What does the second fork protect against?

Question 3

3Why reopen fds 0, 1 and 2 on /dev/null instead of just closing them?

Question 4

4A daemon crashed with SIGKILL and left its PID file. With the lock-based design, what happens at the next start?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Run the explainer's daemon, find it with ps, and check its PPID, session ID and TTY. Then find its log lines in the journal.

  2. Exercise 2medium

    Combine daemonize and write_pidfile into a daemon that refuses to start twice. Start it, try a second copy, read the PID file, then stop it with that PID.

  3. Exercise 3hard

    Make the original process exit only after the daemon has finished starting, with exit code 0 on success or 1 on failure, using a pipe between the first process and the final daemon.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I still need to daemonize if I use systemd?
No. Run in the foreground with Type=simple, exec or notify. systemd handles the background, the logs and the PID; forking only adds complexity.
What is the difference between nohup and a real daemon?
nohup only makes the command ignore SIGHUP and redirects output to nohup.out. The process stays in the shell's session and keeps the terminal's other ties; a daemon fully detaches.
Where should a PID file go?
In /run (often /run/name/name.pid for non-root daemons), which is a tmpfs cleared at boot, so stale files never survive a reboot.
Why do daemons reload on SIGHUP?
A daemon has no terminal, so it will never receive a real hangup. The unused signal became the convention for re-reading configuration.

Go deeper

ShareXLinkedInWhatsApp