fork() and exec()
One of the most important ideas in Linux is that a running process can create
another process.
This is primarily done through two system calls:
- fork() → create a new process
- exec() → replace a process with a new program
Together, fork() and exec() form the core of
Linux process creation and program execution.
High-Level Idea
User runs command → shell creates child process → child loads new program → program executes
Example:
$ ls -l
The shell itself does not become ls.
Instead:
- The shell calls
fork()
- A child process is created
- The child calls
exec()
- The child becomes the
ls program
- The parent shell continues running
fork()
fork() creates a new process by duplicating the current process.
The newly created process is called the child process.
The original process is the parent process.
Important Behavior
After a successful fork():
- Both parent and child continue execution
- Both processes start at the next instruction after fork()
- Each process gets its own PID
Simple fork() Example
#include <stdio.h>
#include <unistd.h>
int main() {
fork();
printf("Hello from process\\n");
return 0;
}
Because both parent and child execute the print statement, the message usually appears twice.
fork() Return Values
pid_t pid = fork();
- 0 → running inside child process
- > 0 → running inside parent process
- -1 → fork failed
Common Pattern
pid_t pid = fork();
if (pid == 0) {
// child process
} else {
// parent process
}
exec()
exec() replaces the currently running program with another program.
fork() creates a process.
exec() transforms that process into a different program.
Key Idea
After a successful exec() call:
- The old program is gone
- The process now runs the new program
- The PID remains the same
Example
#include <unistd.h>
int main() {
execl("/bin/ls", "ls", "-l", NULL);
return 0;
}
This process becomes the ls program.
fork() + exec() Together
This is the classic Linux process-launch pattern.
pid_t pid = fork();
if (pid == 0) {
execl("/bin/ls", "ls", "-l", NULL);
} else {
// parent continues running
}
What Happens Internally
Shell Process
↓
fork()
↓
Child Process Created
↓
exec()
↓
Child Becomes New Program
Why Linux Uses This Design
The separation of process creation and program execution gives Linux enormous flexibility.
- Shells can launch programs
- Servers can spawn workers
- Daemons can create helper processes
- Pipelines and redirection become possible
- Job control becomes manageable
Related Concepts
- PID (Process ID)
- Parent and child processes
- Process scheduling
- Signals
- stdin / stdout / stderr
- Shell command execution
Conceptual Summary
Linux process execution works because:
fork() creates a process,
and
exec() turns that process into a new running program.
Visual Model
Follow the lifecycle of a Linux process from creation through
program execution.