Skip to content
systemcoding.dev
Systems Programming

Detach from the controlling terminal with setsid after fork

Detach a daemon from its terminal by forking, exiting the parent and calling setsid in the child on Linux 6.12, so closing the terminal cannot hang it up.

2 min read
Summarize in AI

A program started from a shell belongs to the shell's session and process group, and its controlling terminal sends it SIGHUP when the terminal closes. A daemon must leave all of that. setsid creates a new session with the caller as leader and no controlling terminal, but it fails with EPERM for a process group leader, which a freshly started program often is. The fix is to fork first: the child is never a group leader, so the call succeeds.

detach.cc
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid > 0) {
        printf("daemon pid %d\n", (int)pid);
        _exit(0);
    }

    if (setsid() < 0) { perror("setsid"); _exit(1); }

    sleep(60);
    return 0;
}
Shell
./detach
ps -o pid,ppid,sid,tty,comm -C detach
Text
daemon pid 4210
    PID    PPID     SID TT       COMMAND
   4210       1    4210 ?        detach

The session id equals the pid, which is what a session leader looks like, and TT is ? for no terminal. The parent exited, so the kernel re-parented the child to pid 1 (or the nearest subreaper).

The parent calls _exit, not exit, so buffered output inherited from the parent is not flushed twice. Per [setsid(2)](https://man7.org/linux/man-pages/man2/setsid.2.html), the new leader may still acquire a controlling terminal by opening a terminal device without O_NOCTTY, which the classic double-fork guards against with a second fork. If you run under systemd, you need none of this: a plain foreground process with Type=simple is the supported way.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.