KatInterview

End-to-End Flow: What Happens When a Shell Runs a Command

System DesignModel answer
MediumModel answerSystem Designlinuxoperating-systemssyscalls

Last updated

Trace every layer from keypress to process exit when a shell executes a directory-listing command, covering process creation, syscalls, and filesystem interactions.

Shell Command Execution: A Full System Walkthrough

When a developer types a command like ls into a terminal and hits Enter, a surprising number of moving parts collaborate to produce those few lines of output. Being able to narrate that sequence — layer by layer — demonstrates a solid mental model of how Unix-like systems actually work.

Your task

Walk through the complete lifecycle of running ls in an interactive shell on a Linux system. Your explanation should cover each of the following stages:

  • What the shell does before any process is created (input handling, name resolution)
  • How a new process is created and how the executable is loaded
  • Which kernel subsystems are involved and which system calls are made
  • How the kernel and filesystem cooperate to read directory contents
  • How the output makes its way back to the terminal
  • How behavior changes when common flags are used: -l, -a, and -R

What a strong answer looks like

A complete answer names the actual system calls at each step, distinguishes what the kernel handles from what libc or the dynamic linker handles, and explains why certain flags are significantly more expensive than others. Quantifying the complexity difference between plain ls and ls -l is a good way to show depth. Mentioning how you would verify any of this empirically (for example, with strace) is a plus.

You do not need to write code, but concrete syscall names, data structures, and kernel concepts should appear throughout your answer.

Hints

Hint 1

Before any process is created, the shell has to figure out which binary to run. Think about what order it checks things in — aliases, builtins, PATH — and how it avoids repeating that search every time.

Hint 2

fork/exec is the core of process creation, but there's a handoff between the kernel and the dynamic linker before main() ever runs. What does each one actually do?

Hint 3

Plain `ls` and `ls -l` look similar from the outside, but their syscall counts are very different. What information is missing from a directory entry that forces `-l` to do extra work?