linux-sysprog · advanced · ~15 min

Order the daemonisation steps

The double-fork daemonise sequence.

Challenge

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 child
  • 3 = second fork
  • 4 = chdir /
  • 5 = umask 0
  • 6 = close stdin/stdout/stderr
  • 7 = reopen them on /dev/null

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 step number.

Output format

Next step (or -1).

Constraints

Pure lookup.

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.