linux-sysprog · beginner · ~15 min
Decode the three-way meaning of fork's return value.
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.
Implement int fork_role(int ret) that classifies a fork() return value ret into -1 (error), 0 (child), or 1 (parent).
ret: a value as returned by fork() (may be negative, zero, or positive).-1 if ret < 0, 0 if ret == 0, 1 if ret > 0.
fork_role(-1) -> -1 (error)
fork_role(0) -> 0 (child)
fork_role(4321) -> 1 (parent, child PID 4321)
ret: a fork() return value (negative, zero, or positive).
-1 error, 0 child, 1 parent.
ret is the return value of a fork() system call.
int fork_role(int ret) {
/* TODO */
return -1;
}
Confusing child and parent return values: 0 is child, positive PID is parent.
ret < 0 (fork error), ret == 0 (child process), ret > 0 (parent process).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.