Course contentsShow
← Linux
Lesson 233 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Shell Forking Behavior

Deepen your knowledge of how the kernel spawns sub-processes.

In this lesson, you will learn how the Linux kernel uses a "copy-on-write" mechanism to create new processes when you run commands in your shell.

The Birth of a Process

When you type a command into your terminal—like ls or grep—the shell doesn't just run it directly. Instead, it performs two distinct steps: forking and executing.

Think of "forking" as the shell creating a biological clone of itself. The kernel takes the current shell process, duplicates its memory, file descriptors, and environment variables, and creates an identical child process. At this precise moment, both the parent shell and the child process are executing the exact same code.

The Fork-Exec Pattern

If the child process remained an identical copy, it would just be another shell waiting for input. To transform it into the command you requested, the kernel uses the exec system call. This replaces the child’s memory space with the code of your target program (e.g., the ls binary).

Here is what that looks like conceptually:

# Conceptual flow of running 'ls'
# 1. Shell calls fork() -> Child process is born
# 2. Child process calls exec("/bin/ls") -> Child becomes 'ls'
# 3. Parent shell calls wait() -> Shell pauses until 'ls' finishes

Why "Copy-on-Write"?

You might wonder if copying the entire memory of a shell is slow. Thanks to a clever optimization called Copy-on-Write (COW), the kernel doesn't actually copy all that data immediately. Instead, the parent and child share the same physical memory space.

The kernel only creates a unique copy for the child if the child attempts to modify its data. Because exec immediately replaces the child's entire memory with a new program, most of the original shell's data is never actually duplicated, making the process incredibly fast and memory-efficient. This is why you can launch hundreds of processes per second without crashing your system.

Key Takeaway: Forking creates a structural clone of the shell, which the kernel then instantly transforms into your desired command using the exec system call, optimized by memory-sharing techniques.