~/ learn/ comp-325/ cards/ From a toy to something that stays up
1 of 12

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

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/d8917a85-3cf7-4de8-9d5f-c96abdea6c54/flashcard utf-8 LF