End-to-End Flow: What Happens When a Shell Runs a Command
System DesignModel answerLast 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Full Walkthrough: Shell Command Execution
1. From keypress to command string
The terminal emulator receives your keystrokes and writes them to the pty master. The shell holds the pty slave as its stdin. In interactive mode, bash hands input off to readline, which switches the tty into non-canonical (raw) mode and calls read(0, …) one character at a time — this is what enables line editing and history. When you press Enter, readline delivers the string ls to the shell.
The shell then processes the input in this order:
- Tokenization — split the line into words
- Expansion — resolve aliases (on many systems
lsexpands tols --color=auto), variables, and globs - Command resolution — check functions, then builtins, then walk
$PATH
ls is not a builtin. The shell consults its hash table of previously resolved commands. On a cache miss, it iterates over each directory in $PATH and calls stat on dir/ls until it finds an executable regular file — typically /usr/bin/ls — and caches the result.
2. Process creation
The shell calls fork() — on Linux this is actually clone() under the hood, with copy-on-write memory. In the child process the shell:
- Moves the child into a new process group via
setpgid - Grants that group terminal foreground status with
tcsetpgrp(so Ctrl-C reachesls, not the shell) - Resets any signal handlers
- Applies redirections using
openanddup2
Then the child calls execve("/usr/bin/ls", argv, envp). The parent blocks in waitpid().
3. execve and program startup
Kernel side: The kernel resolves /usr/bin/ls through the VFS, checking the dentry cache at each path component and falling back to disk on a miss. It verifies execute permission on the file, reads the ELF header, and dispatches to the binfmt_elf handler. The handler:
- Tears down the old address space
- Maps the
PT_LOADsegments from the ELF binary - Sees that the binary is dynamically linked and also maps the interpreter listed in
PT_INTERP— typically/lib64/ld-linux-x86-64.so.2 - Builds the new stack (argc, argv, envp, auxiliary vector)
- Marks
O_CLOEXECfile descriptors for closure - Jumps to the dynamic linker's entry point
Dynamic linker side: ld.so opens and mmaps the required shared libraries (libc.so.6, and often libselinux, libcap), performs relocations, and jumps to _start → __libc_start_main → main.
Early work in ls itself:
setlocalereads locale data; collation rules affect sort order- Options are parsed
isatty(1)(implemented as anioctl(TCGETS)) determines whether stdout is a terminal — if not,lsemits one name per line with no colorioctl(TIOCGWINSZ)retrieves terminal width for column formatting- With no arguments, the target defaults to
.
4. Reading the directory
The core sequence of syscalls looks like this:
statx(AT_FDCWD, ".", AT_SYMLINK_NOFOLLOW, ...)
openat(AT_FDCWD, ".", O_RDONLY|O_CLOEXEC|O_DIRECTORY) = 3
getdents64(3, buf, 32768) # returns N bytes of entries
getdents64(3, buf, 32768) # returns 0 = end of directory
close(3)
write(1, "a.txt b.c src\n", ...)
exit_group(0)
openat creates a file description and checks read permission on the directory. getdents64 calls the filesystem's iterate_shared method; on ext4 this walks the directory's block tree (possibly an htree) through the page cache, reading from disk only on a miss.
Each record from getdents64 contains: inode number, record length, d_type, and name. It does not contain size, permissions, owner, or timestamps — those live in the inode, not the directory entry. This distinction is the key to understanding why -l costs more.
glibc's readdir() drains the kernel buffer and issues more getdents64 calls as needed. ls drops names beginning with ., sorts the remainder using strcoll (locale-aware), formats into columns, and flushes via write(1, …).
5. Output and process exit
Bytes written to the pty slave pass through the kernel's line discipline to the pty master. The terminal emulator reads and renders them.
ls calls exit_group(status). The kernel turns it into a zombie and sends SIGCHLD to the shell. waitpid returns, the shell stores the exit code in $?, reclaims terminal foreground with tcsetpgrp, and prints the next prompt.
6. How flags change the cost
| Flag | What changes |
|---|---|
-a | Nothing in the kernel. getdents64 always returns dotfiles; ls simply stops filtering names that start with .. (-A shows dotfiles but omits . and ...) |
-l | One statx (or lstat) per entry to fetch the inode: mode bits, link count, uid/gid, size, mtime, block count. Symlinks also get a readlink. uid and gid are resolved to names via getpwuid/getgrgid through NSS, which may read /etc/passwd and /etc/group or query a network directory. ACL and SELinux markers require lgetxattr/listxattr. For a cold cache on a spinning disk or NFS mount, each statx can be a separate I/O round trip. |
-R | For every subdirectory encountered (identified via d_type, or a stat when d_type is DT_UNKNOWN), ls recurses: another openat/getdents64 loop with a heading line. Symlinked directories are not followed unless -L is given; with -L, coreutils tracks (dev, inode) pairs to detect cycles. |
Complexity and edge cases
For a directory with n entries:
- Plain
ls: O(n) kernel work, O(n log n) sort, a handful ofgetdents64calls ls -l: adds nstatxsyscalls — each a potential cache miss or network round tripls -R: scales with total tree size; each level starts a newopenat/getdents64loop
Edge cases worth knowing:
- No read permission:
openatreturnsEACCES; exit status 2 - Read permission but no execute permission:
getdents64succeeds, butstaton entries fails;-lshows?for all metadata fields; exit status 1 - Race conditions: a file deleted between
getdents64andstatxcausesENOENTon thestatx;lsprints the name with?fields rather than crashing - Empty directories: the first
getdents64returns only.and.., filtered out by default; output is blank
The cleanest way to verify any of this is strace -f ls -l /some/dir 2>&1 | less, which shows every syscall in order.