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.
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.
#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;
}./detach
ps -o pid,ppid,sid,tty,comm -C detachdaemon pid 4210
PID PPID SID TT COMMAND
4210 1 4210 ? detachThe 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.