linux-sysprog · advanced · ~15 min
The double-fork daemonise sequence.
Given one step of the canonical double-fork daemonisation sequence, report which step comes next. This is a pure lookup over a fixed 7-step order — nothing is forked.
Implement int daemonize_step_after(int current) that returns the step following current.
current: a step number from this fixed sequence:1 = first fork (parent exits)2 = setsid in child3 = second fork4 = chdir /5 = umask 06 = close stdin/stdout/stderr7 = reopen them on /dev/nullReturns current + 1 for steps 1 through 6, returns -1 for step 7 (the last step), and returns -1 for any number outside 1..7.
daemonize_step_after(1) -> 2
daemonize_step_after(3) -> 4
daemonize_step_after(7) -> -1 (last step)
daemonize_step_after(0) -> -1 (invalid)
daemonize_step_after(99) -> -1 (invalid)
-1 (no next step).1..7 returns -1.The classic 'double-fork daemonise' has a precise ordering; reordering breaks the daemon's properties (won't survive logout, leaves a controlling terminal, etc).
current: a step number; the canonical order is the 7 fixed steps listed above.
current+1 for steps 1..6, -1 for step 7 or any value outside 1..7.
Valid steps are 1..7. Step 7 and out-of-range inputs return -1.
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.