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:

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:

  1. The shell calls fork()
  2. A child process is created
  3. The child calls exec()
  4. The child becomes the ls program
  5. 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():

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();

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:

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.

Related Concepts

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.