C Reference ยท POSIX and Systems
C fork() function
Reference for fork(): how it duplicates the calling process, what parent and child share, return values, buffering pitfalls, and how to wait for children.
fork() creates a new process by duplicating the calling one. After a successful call there are two processes running the same program, each continuing from the instruction after fork(). The only visible difference is the return value: the parent receives the child's process ID, the child receives 0.
The child gets a copy of the parent's memory (copy-on-write in practice), the same open file descriptors, and the same working directory. Changes made after the fork are private to each process. Most programs call fork() and then, in the child, exec another program; the parent uses waitpid to collect the result.
#include <unistd.h> pid_t pid = fork(); if (pid == 0) { /* child */ } else if (pid > 0) { /* parent */ } else { /* fork failed */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
#include <unistd.h> pid_t fork(void);
Parameters: none.
Returns: in the parent, the process ID of the child (positive). In the child, 0. On failure, -1 in the parent and no child is created.
Errors: EAGAIN (a process or memory limit was reached) and ENOMEM (not enough kernel memory). The error is reported through errno.
What is shared and what is copied
| Item | After fork |
|---|---|
| Memory (stack, heap, globals) | Copied; each process changes its own copy |
| Open file descriptors | Duplicated; both refer to the same open file, so they share the file offset |
| Process ID, parent ID | New for the child |
| Signal handlers | Inherited; pending signals are cleared in the child |
| Threads | Only the calling thread exists in the child |
| Memory locks, timers | Not inherited |
Usage notes
- Flush stdio buffers before forking. If the parent has unflushed text in the
stdoutbuffer, both processes inherit it and print it twice. This is the classic "why is my output duplicated" bug, and it shows up when output goes to a file or pipe, where stdout is fully buffered. - Output order between processes is not defined. Without
waitpidor another synchronization, parent and child lines can appear in either order. Examples that must be deterministic wait before printing. - Use
_exit()in children that must not flush.exit()runsatexithandlers and flushes stdio buffers, which can duplicate output or touch state the parent still owns. After a failedexec, call_exit. - Reap your children. A child that has exited but was never waited for stays as a zombie entry in the process table. Call
waitorwaitpid, or setSIGCHLDtoSIG_IGNwhere the platform allows. - Forking a multi-threaded program is dangerous. Only the calling thread survives, so locks held by other threads stay locked forever in the child. Until you
exec, call only async-signal-safe functions there. - Cost:
forkis cheap because of copy-on-write, but a large address space still means page tables to copy.posix_spawnandvforkavoid that when all you want is to start a program. - A "fork bomb" is a loop that forks without bound; per-user process limits (
RLIMIT_NPROC) exist to stop it. - Windows has no
fork. On such systems useCreateProcessor a library abstraction.
Related
- exec family, wait and waitpid, pipe
- unistd.h, signal.h
- Tutorial: System calls, Signals