linux-sysprog · advanced · ~15 min
The double-fork daemonise sequence.
The canonical daemonise sequence has 7 steps. Implement
int daemonize_step_after(int current) returning the step that follows
current, or -1 if current is the last step. Step numbers:
1 = first fork (parent exits)2 = setsid in child3 = second fork4 = chdir /5 = umask 06 = close stdin/stdout/stderr7 = reopen them on /dev/nullThe classic 'double-fork daemonise' has a precise ordering; reordering breaks the daemon's properties (won't survive logout, leaves a controlling terminal, etc).
Current step number.
Next step (or -1).
Pure lookup.
int daemonize_step_after(int current) { /* TODO */ (void)current; return -1; }
Swapping setsid before fork (kills the daemon's reparent).
Invalid current step.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.