linux-sysprog · beginner · ~15 min

Interpret fork's return

Decode the three-way meaning of fork's return value.

Challenge

fork() returns once in each of two processes, and its return value tells each side who it is: negative on error, 0 in the child, and the child's PID (positive) in the parent.

Task

Implement int fork_role(int ret) that classifies a fork() return value ret into -1 (error), 0 (child), or 1 (parent).

Input

  • ret: a value as returned by fork() (may be negative, zero, or positive).

Output

-1 if ret < 0, 0 if ret == 0, 1 if ret > 0.

Example

fork_role(-1)     ->   -1   (error)
fork_role(0)      ->   0    (child)
fork_role(4321)   ->   1    (parent, child PID 4321)

Input format

ret: a fork() return value (negative, zero, or positive).

Output format

-1 error, 0 child, 1 parent.

Starter code

int fork_role(int ret) {
    /* TODO */
    return -1;
}

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