linux-sysprog · intermediate · ~15 min

Spawn child and collect exit code

`fork`, `_exit`, `waitpid`; the parent/child split.

Challenge

Fork a child process, have it exit with a given code, and collect that code in the parent.

Task

Implement int spawn_exit(int code) that:

  1. fork()s,
  2. in the child, calls _exit(code),
  3. in the parent, waitpid()s for the child and returns its exit status (the value WEXITSTATUS extracts).

No main — the grader calls it.

Input

One int argument code — the exit code the child should produce (e.g. 0..42).

Output

The child's exit status as an int (equal to code on a normal exit), or -1 on a fork/wait error.

Example

spawn_exit(0)    ->   0
spawn_exit(7)    ->   7
spawn_exit(42)   ->   42

Edge cases

  • A fork failure returns -1.

Rules

  • Use _exit in the child (not exit) to skip atexit handlers; waitpid in the parent, then WEXITSTATUS.

Input format

One int argument code (the exit code the child should produce).

Output format

The child's exit status as an int (equals code on normal exit), or -1 on error.

Constraints

Child uses _exit; parent uses waitpid then WEXITSTATUS.

Starter code

#include <unistd.h>
#include <sys/wait.h>

int spawn_exit(int code) {
    /* TODO */
    return -1;
}

Common mistakes

Creating zombie processes by failing to reap child with wait/waitpid; forgetting that code after successful execvp() is never reached.

Edge cases to handle

Fork failure (EAGAIN); child process crashing with signal; parent terminating before child; waitpid() with WNOHANG on running child.

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