linux-sysprog · advanced · ~15 min

Order the daemonisation steps

The double-fork daemonise sequence.

Challenge

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.

Task

Implement int daemonize_step_after(int current) that returns the step following current.

Input

  • current: a step number from this fixed sequence:
    • 1 = first fork (parent exits)
    • 2 = setsid in child
    • 3 = second fork
    • 4 = chdir /
    • 5 = umask 0
    • 6 = close stdin/stdout/stderr
    • 7 = reopen them on /dev/null

Output

Returns current + 1 for steps 1 through 6, returns -1 for step 7 (the last step), and returns -1 for any number outside 1..7.

Example

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)

Edge cases

  • Step 7 returns -1 (no next step).
  • Any value not in 1..7 returns -1.

Why this matters

The classic 'double-fork daemonise' has a precise ordering; reordering breaks the daemon's properties (won't survive logout, leaves a controlling terminal, etc).

Input format

current: a step number; the canonical order is the 7 fixed steps listed above.

Output format

current+1 for steps 1..6, -1 for step 7 or any value outside 1..7.

Constraints

Valid steps are 1..7. Step 7 and out-of-range inputs return -1.

Starter code

int daemonize_step_after(int current) { /* TODO */ (void)current; return -1; }

Common mistakes

Swapping setsid before fork (kills the daemon's reparent).

Edge cases to handle

Invalid current step.

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.