What does fork() return, and how does a program use that value?
fork() creates a copy of the calling process. It returns 0 in the child, the child's PID in the parent, and -1 if creation failed. Programs branch on that value to run different code in each.
Explain it simply
Fork is like photocopying a form and handing the copy to a friend. Both of you now hold the same form, filled up to the same line, and continue from there. To tell the original from the copy, fork gives each a different answer to "what did fork return?".
- In the child, fork returns
0. - In the parent, fork returns the child's process ID (a positive number).
- On failure (no memory, process limit reached), it returns
-1and no child exists.
The child starts with a copy of the parent's memory, registers and open files, and resumes at the instruction right after the fork() call.
Example
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
printf("fork failed\n");
} else if (pid == 0) {
printf("child\n");
} else {
printf("parent of %d\n", pid);
}
return 0;
}
// prints: "child" and "parent of <child pid>" in either orderThe order of the two lines is not fixed; the scheduler decides which process runs first. If you need an order, make the parent call wait().
What to say in the interview
"fork returns 0 to the child, the child's PID to the parent, and -1 on error. I check for the error case first, then use pid == 0 for child code and the else branch for parent code. The output order between them is not guaranteed unless the parent waits."
Common mistakes
- Assuming the parent always prints first.
- Forgetting the -1 case.