Operating Systems18 min readAdvanced

System Calls & The Shell

What happens when you press Enter on `cat file.txt | grep cs`.

Tracing the lifecycle of a command

When you type `cat file.txt | grep cs` and hit Enter, your shell does a lot:

  • 1. Tokenize the command line.
  • 2. Detect the pipe '|' — there are two programs to run.
  • 3. Create a pipe (a kernel buffer with a read end and a write end) via the `pipe()` syscall.
  • 4. fork() to create a child process. Child redirects its stdout to the pipe's write end, then exec()s `cat file.txt`.
  • 5. fork() again. Child redirects its stdin to the pipe's read end, exec()s `grep cs`.
  • 6. The shell waits on both children.
  • 7. As `cat` reads file blocks and writes them, the kernel buffers in the pipe; `grep` reads from the pipe; matching lines go to your terminal.
💡 Tip
fork(), exec(), and pipe() are about 50 years old and still power every shell pipeline you write. Read Kernighan & Ritchie or the APUE textbook — this stuff is foundational.