student@ubuntu:~$
Topic Week 9 2 min overview

Processes (fork & exec)

How Unix spawns programs, and why every shell looks the way it does

In a nutshell

fork() creates a near-identical copy of the calling process. The two processes (parent and child) return from fork with different return values: the child gets 0, the parent gets the child’s PID. That is the only way Unix creates processes. exec*() replaces the current process’s memory with a new program. The canonical shell loop is fork → in the child, exec the requested program; in the parent, wait for the child to finish.

Why it matters

Every Unix program that launches another program is using fork/exec at some level. Shells, web servers, build systems (make), IDE tooling — all rely on this dance. It is also the foundation of CSCD 340 (Operating Systems). Getting fluent here means you can read and write the source of bash, sshd, nginx, and similar tools.

Key takeaways

  • fork() returns twice (once in parent, once in child) with different values. if (pid == 0) is the child branch; else is the parent branch.
  • After fork, both processes run the same code from where fork returned, until one of them does something different.
  • exec*() replaces the process image. Code after a successful exec call never runs; the new program has taken over. Check the return value to detect failure.
  • wait() / waitpid() block the parent until a child exits and hand back the exit code.
  • Process IDs (pid_t) identify running processes. getpid() and getppid() give yours and your parent’s.

Lessons in this topic

Lesson What it covers
fork & exec The fork/exec/wait idiom, writing a minimal shell

Practice and deep dives

Practice this topic: Fork & Exec drill, or browse the practice gallery.

What comes next

IPC (pipes & signals) — how two processes talk to each other.