Skip to content

Writing a daemon

Prefer systemd over self-daemonizing; if you must daemonize, fork twice, chdir, reset umask, redirect stdio.

Modern daemon rules

  1. Prefer systemd

    Type=simple lets systemd manage the process. No daemonizing code needed. The process just runs in the foreground.

  2. Fork twice if you must daemonize

    fork → parent exits → setsid → fork again → grandparent exits. Child has no TTY, is a session leader.

  3. Chdir to /

    A daemon should not keep the cwd pinned to a filesystem; that prevents unmounting.

  4. Reset umask

    umask(0) so the daemon's file creation is not inherited from the shell.

  5. Redirect stdio

    freopen('/dev/null', 'r', stdin); freopen('/dev/null', 'w', stdout); freopen('/dev/null', 'w', stderr);

  6. Log to syslog or journald

    Not to stdout. Logs need to survive the daemon's restart.