← back to hub

fork() & exec()

1. The Shell is just a Process

When you type `./app.exe` in the terminal, how does the OS run it?

  • The Shell (bash, zsh, cmd) is just a normal User Process. It does not have the power to magically spawn new processes from nothing.
  • To run a new command, the Shell must literally clone itself, and then brainwash the clone into becoming the new program.

2. The Clone: fork()

The OS System Call that creates a new process by duplicating the calling process.

  • The OS creates a new PCB (Process Control Block).
  • The OS completely duplicates the Parent's memory pages (Code, Variables, Stack) into the Child's memory space. They are now identical twins.
  • The Magic Trick: `fork()` is called ONCE, but it returns TWICE. It returns the Child's PID to the Parent, and it returns `0` to the Child. This lets the identical twins know who they are!

3. The Brainwash: exec()

If the clone is identical to the Shell, how do we run the new app?

  • The Child uses the `if (pid == 0)` check to realize it is the child.
  • It immediately calls `exec("app.exe")`.
  • The OS intercepts this, wipes the Child's copied memory, and replaces it with the code and data from `app.exe`. The clone is now running the new program!
OS Process Table (PCBs)
PIDPPIDNameState
10011bash (Shell)RUNNING
Parent Memory Space (PID 1001)
Shell Logic[Code Page]
Env Vars[Data Page]
bash()[Stack Page]
⬇ DUPLICATING MEMORY PAGES ⬇
Child Memory Space (PID 1002)
C Code Execution
int main() {
  printf("Shell> ./app.exe\n");
  pid_t pid = fork();

  if (pid > 0) {
    wait(NULL); // Parent waits
  } else if (pid == 0) {
    exec("./app.exe"); // Brainwash
  }
}