fork()¶
Purpose¶
fork() creates a child process by duplicating the calling process.
After fork(), both parent and child continue execution from the next instruction, but receive different return values.
Header¶
Prototype¶
Return Value¶
| Return | Meaning |
|---|---|
0 |
Running in the child process. |
> 0 |
Running in the parent process; value is child PID. |
-1 |
Error. Check errno. |
Minimal Example¶
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return -1;
}
if (pid == 0) {
/* Child process */
_exit(0);
}
/* Parent process */
waitpid(pid, NULL, 0);
Common Pitfalls¶
- Forgetting to close unused file descriptors in parent or child.
- Calling non-async-signal-safe code after
fork()in a multi-threaded process beforeexec(). - Forgetting to reap child processes, causing zombies.