Become a daemon: fork, leave, detach, and settle somewhere safe
Become a daemon: fork, leave, detach, and settle somewhere safe
Answer
pid_t pid = fork(); if (pid < 0) { perror("fork"); exit(1); } if (pid > 0) _exit(0); /* parent leaves; child is re-parented to init */ if (setsid() < 0) { perror("setsid"); exit(1); } (void)umask(027); if (chdir("/") < 0) { perror("chdir"); exit(1); }
`setsid()` works here only because the fork guarantees the child is not a process-group leader; called before the fork it would fail with `EPERM`. `chdir("/")` frees the filesystem the daemon started in and puts any core file somewhere findable.
S&K 3e ch21 §21.4–21.14; ch20 §20.11