$linuxjunkies
>

fork

also: fork()

A system call that creates a new process by duplicating the current process. The child process is an identical copy of the parent, but runs independently with its own process ID.

The fork() system call is fundamental to Unix/Linux process creation. When a process calls fork, the kernel creates a new child process that is nearly identical to the parent: it has the same code, data, stack, and file descriptors. However, they are separate processes with different process IDs (PIDs).

After fork returns, both parent and child continue executing from the same point in the code, but fork() returns 0 to the child and the child's PID to the parent. This allows the program to determine which process it is and behave accordingly.

A common pattern is for the child to then call exec() to replace its memory image with a different program. For example, when you type a command in your shell, the shell forks a child process, and that child execs the command program.

Example: pid = fork(); creates a child. If pid > 0, you're in the parent; if pid == 0, you're in the child; if pid < 0, the fork failed.

Related terms