linux-sysprog · advanced · ~30 min

Order of operations to daemonize a process

Memorize the conventional double-fork daemon recipe.

Challenge

Return the canonical daemonization steps as an array of integer constants:

enum {
  STEP_FORK_1=1, STEP_SETSID=2, STEP_FORK_2=3, STEP_CHDIR_ROOT=4,
  STEP_UMASK_0=5, STEP_CLOSE_STDIN=6, STEP_REDIRECT_STDOUT_NULL=7,
  STEP_REDIRECT_STDERR_NULL=8
};
int daemon_steps(int *out, int max);

Fill out with the steps in the correct order, returning the count.

Why this matters

Becoming a 'real' daemon requires a precise dance: fork twice, setsid, chdir /, umask 0, close fds, redirect stdio. Get the order wrong and your daemon leaks a controlling terminal or stays in the session group — both are pretty bad bugs.

Input format

max >= 8.

Output format

Sequence of 8 step ids in correct order.

Constraints

No syscalls actually executed.

Starter code

enum {
  STEP_FORK_1=1, STEP_SETSID=2, STEP_FORK_2=3, STEP_CHDIR_ROOT=4,
  STEP_UMASK_0=5, STEP_CLOSE_STDIN=6, STEP_REDIRECT_STDOUT_NULL=7,
  STEP_REDIRECT_STDERR_NULL=8
};
int daemon_steps(int *out, int max) { /* TODO */ return 0; }

Common mistakes

setsid before the first fork (fails — the parent is process group leader); only forking once (your daemon can still acquire a controlling tty); chdir after closing fds (chdir is fine but order is conventional).

Edge cases to handle

max < 8 — return as many as fit.

Complexity

O(1).

Up next

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