How does Linux create new processes (fork and exec)?
fork() clones the current process into a child; exec() then replaces the child's code with the new program — clone, then transform.
* fork() clones the parent into a child; exec() overlays a new program in the same PID; the parent wait()s to reap it. *
Linux has no single "create a process from this file" call. Instead it splits the job in two, and understanding why is the whole point. fork() duplicates the calling process, giving you a second process that's identical except for its new PID. exec() then overwrites that copy's memory with a different program, keeping the same PID. Clone first, become-something-else second.
fork() — make an exact copy of the parent:
- the child inherits file descriptors, environment, and permissions
- the child gets a brand-new PID
- it "returns twice":
0in the child, the child's PID in the parent — that's how each side knows who it is
exec() — replace the running program:
- same PID, but the code, data, and stack are swapped for the new program
- there's no going back; the old program is gone
Splitting it this way is powerful: between the fork and the exec, the child can adjust its inherited state — redirect stdout to a file, change directory, drop privileges — before the new program starts. That gap is how shells implement redirection and pipes.
Typical flow:
Parent Process
│
├── fork() ──→ Child Process (copy of parent)
│ │
│ └── exec() ──→ New Program
│
└── wait() ──→ Waits for child to finish
Example: When you type ls in bash:
- Bash calls
fork()→ creates child bash - Child calls
exec("ls")→ becomesls lsruns and exits- Parent bash continues
Go deeper:
fork–exec (Wikipedia) — the clone-then-overlay pattern, the twice-returning fork(), and why shells fork before exec.