Skip to content
Tutorials Center
My learning

Topics

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.

C
#include <unistd.h>

pid_t pid = fork();
if (pid == 0) { /* child */ }
else if (pid > 0) { /* parent */ }
else { /* fork failed */ }

Try it

C Parent and child are separate processes

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.

C Several children, results in order

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

C
#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 stdout buffer, 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 waitpid or 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() runs atexit handlers and flushes stdio buffers, which can duplicate output or touch state the parent still owns. After a failed exec, 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 wait or waitpid, or set SIGCHLD to SIG_IGN where 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: fork is cheap because of copy-on-write, but a large address space still means page tables to copy. posix_spawn and vfork avoid 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 use CreateProcess or a library abstraction.