Lifecycle of Running ls -l in a Linux Shell
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Suppose you are logged into an interactive POSIX shell on Linux (for instance, bash), enter ls -l, and press Return. Walk through the complete execution path — across user-space libraries, C runtime wrappers, and the Linux kernel — from the initial key press until the formatted directory listing appears in your terminal window and a fresh prompt is ready.
Structure your walk-through around these six stages:
- Keystroke capture and command parsing: How characters reach the shell, get split into tokens, undergo shell expansions, and are classified as aliases, functions, built-ins, or external binaries.
- Executable discovery: How the shell locates the
lsprogram on disk using its command cache andPATHdirectories. - Spawning and loading the binary: Which system calls (
fork/cloneplusexecve, orvfork/posix_spawn) create the child process, preserve or rewire standard descriptors (0,1,2), and map the ELF image into virtual memory. - Shared-library linking and C startup: How
ld.somaps required shared objects (such aslibc.so) and resolves symbols prior to invokingmain(). - Enumerating entries and querying attributes: Which kernel Virtual File System (VFS) calls
lsmakes to read filenames (getdents64) and retrieve-lmetadata (statxornewfstatat). - Rendering text and reaping the child: How bytes travel from
write()across the pseudoterminal (pty), how the child terminates (exit_group), and how the parent shell collects its exit status (wait4/waitpid) before printing the next prompt.
Scope & Expectations
- Name concrete Linux/POSIX system calls at each stage and clearly separate what happens in unprivileged user space versus privileged kernel space.
- Explain process-group job control, memory management optimizations during process creation, and dynamic linking prior to
main(). - Note how terminal line disciplines, TTY detection (
isatty), or shell pipelines alter buffering and output behavior.
Step-by-step walkthrough
Keystrokes, pseudoterminals, and kernel transitions
Before
lseven exists, three programs cooperate across user space (unprivileged application mode, CPU ring 3) and kernel space (privileged OS mode, CPU ring 0): the terminal emulator (orsshdover SSH), the kernel's TTY / line discipline layer (N_TTY), and your interactive shell (bash). They connect through a pseudoterminal (pty) — a virtual bidirectional pipe pair consisting of a master side held by the terminal emulator and a slave device (/dev/pts/N) opened bybashas file descriptors (integer handles into the process's open-file table)0(stdin),1(stdout), and2(stderr).[Keyboard] | GUI key event ('l', 's', ' ', '-', 'l', Return) v [Terminal Emulator] (user space) | write(pty_master_fd, ...) ---> CPU "syscall" instruction (ring 3 -> ring 0) v [Linux Kernel: pty master -> N_TTY Line Discipline -> /dev/pts/N] (kernel space) | wakes sleeping bash from read(0, buf, 1) v [bash + GNU Readline] (user space)- Raw-ish editing vs. canonical mode: by default,
N_TTYruns in canonical mode (ICANON+ECHO), meaning the kernel buffers characters, handles Backspace itself, echoes letters back to the screen, and wakesread()only when a newline arrives. However, interactivebashuses GNU Readline (to support arrow keys, command history, andTabcompletion): before printing your prompt, Readline callstcsetattr()(ioctl(0, TCSETS, ...)) to disableICANONandECHOsobashwakes on every keystroke viaread(0, buf, 1)and echoes characters itself. (ISIGremains enabled soCtrl-Cmakes the kernel sendSIGINTto the foreground process group.) - How a system call crosses into the kernel: each
read()wrapper inglibcplaces syscall number0(SYS_read) into registerrax, executes the x86-64syscallinstruction to jump into ring 0 on a kernel stack, sleeps on a kernel wait queue while you think (consuming 0% CPU), and returns viasysretonce bytes arrive. - Pressing
Return: sends carriage return\r(0x0d). Readline finishes collecting"ls -l", restores the terminal back to standard canonical + echo mode so the upcoming child process inherits a normal terminal, appends the line to shell history, and hands"ls -l"tobash's parser.
- Raw-ish editing vs. canonical mode: by default,
Tokenizing, expansions, aliases, and command classification
The Linux kernel has no idea what shell syntax, quotes, or
*wildcards mean —bashparses and transforms the command line entirely in user space:- Tokenizing and alias substitution:
bashsplits"ls -l"into tokens around unquoted whitespace. Because this is an interactive shell,bashchecks whether the first word matches an alias (a pure text macro). Most Linux distributions definealias ls='ls --color=auto'in~/.bashrc, transforming the words into["ls", "--color=auto", "-l"]. - Shell expansions (in strict order): brace expansion (
{a,b}) -> tilde (~), variable ($HOME), arithmetic, and command substitution ($(...)) -> word splitting -> pathname (glob) expansion -> quote removal. Forls -l, nothing changes; if you had typedls -l *.log,bashitself would scan the current directory and replace*.logwith["app.log", "db.log"]before launchingls(lsnever sees the*character). Any redirections like> listing.txtare stripped out to be wired up later in the child. - Command classification: for a command name containing no
/slash,bashchecks in order:- Shell function -> Shell builtin (like
cd,export, orulimit, which must execute directly inside thebashprocess without spawning a child, because a child process cannot modify its parent's working directory or environment variables) -> External executable.
- Shell function -> Shell builtin (like
$ type -a ls ls is aliased to `ls --color=auto' ls is /usr/bin/ls ls is /bin/ls(On modern merged-
/usrLinux distributions,/binis a symbolic link to/usr/bin.)- Tokenizing and alias substitution:
Resolving /usr/bin/ls via the hash cache and PATH
Because
lsis neither a function nor a builtin, and"ls"contains no/,bashmust locate the executable file in user space:- Internal hash table first:
bashkeeps an in-memory dictionary mapping previously run command names to their resolved paths (viewable withhash). On a cache hit,bashskips directory probing completely. - Walking
$PATHon a first run:bashreads itsPATHenvironment variable (for example,/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin), splits on:, joins each directory with"/ls", and probes file metadata vianewfstatat()(orstat()) until it finds a regular file with execute permission for the current user:
newfstatat(AT_FDCWD, "/usr/local/sbin/ls", ...) = -1 ENOENT (No such file) newfstatat(AT_FDCWD, "/usr/local/bin/ls", ...) = -1 ENOENT newfstatat(AT_FDCWD, "/usr/sbin/ls", ...) = -1 ENOENT newfstatat(AT_FDCWD, "/usr/bin/ls", ...) = 0 (Found! Cache ls -> /usr/bin/ls)If every
PATHdirectory misses,bashprintscommand not foundand sets exit status127; if a matching file exists without execute permissions, exit status is126.- Internal hash table first:
Spawning the child with fork/clone, job control, and execve
Unix deliberately splits launching a program into two system calls —
fork()(duplicate the current process) followed byexecve()(replace the child's memory with a new program) — because the brief gap between them lets the shell configure redirections, signals, and process groups using ordinary code:- Cloning the process (
fork->clone): in modernglibc, callingfork()invokes the Linuxclone()system call (clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD)). The kernel assigns a new PID, duplicates the open file-descriptor table (so child fds0,1, and2still point to/dev/pts/N), and marks private memory pages Copy-on-Write (CoW) so physical RAM is shared read-only rather than copied upfront.fork()returns twice: child PID in parentbash,0in the child. - Foreground job control and signals: both parent and child call
setpgid()to put the child in its own process group, andtcsetpgrp()(ioctlTIOCSPGRP) makes that group the terminal's foreground group soCtrl-C(SIGINT) orCtrl-Z(SIGTSTP) targetslsinstead of killingbash. The child also resets signal handlers ignored by interactivebash(SIGQUIT,SIGTSTP) back toSIG_DFLand applies any I/O redirections (open+dup2+close). - Loading the ELF binary (
execve): the child callsexecve("/usr/bin/ls", ["ls", "--color=auto", "-l"], envp). Inside the kernel:- Verifies execute permissions and inspects the file's magic header bytes (
\x7fELFselects the ELF — Executable and Linkable Format — binary loader;#!would recursively invoke an interpreter script). - Discards the inherited
bashvirtual memory mappings (the point of no return) while preserving PID, working directory, and open descriptors not markedO_CLOEXEC. - Sets up lazy virtual memory mappings (
mmap) forls'sPT_LOADcode and data segments at randomized addresses (ASLR, Address Space Layout Randomization). Actual bytes are not read eagerly — they fault in from the kernel page cache on first CPU access (demand paging). - Reads the
PT_INTERPheader (/lib64/ld-linux-x86-64.so.2), maps that dynamic linker into memory, builds the initial user stack (argc,argvpointers,envppointers, and the auxiliary vector passing kernel metadata like page sizeAT_PAGESZ,ls's real entry pointAT_ENTRY, and the vDSO fast clock/gettimeofday page), and jumps told.so's entry point on return to user space.
- Verifies execute permissions and inspects the file's magic header bytes (
Here is the core parent-child protocol in Python, which invokes the exact same POSIX primitives:
import os import shutil import sys def run_external_command(argv: list[str]) -> int: # Step 1: Search $PATH in user space, just like bash does on a hash miss. binary_path = shutil.which(argv[0]) if binary_path is None: print(f"{argv[0]}: command not found", file=sys.stderr) return 127 # Step 2: Clone the shell process; child inherits fds 0, 1, 2 (/dev/pts/N). child_pid = os.fork() if child_pid == 0: try: # Step 3: Replace child memory image with /usr/bin/ls; never returns on success. os.execv(binary_path, argv) except OSError: # Must use _exit so a failed child never flushes parent stdio buffers twice. os._exit(126) # Step 4: Parent waits for child to terminate and reaps its zombie entry. _, raw_status = os.waitpid(child_pid, 0) return os.waitstatus_to_exitcode(raw_status)- Cloning the process (
Dynamic linking (ld.so) and C runtime startup before main()
The first user-space instructions executed in the new process belong to the dynamic linker (
ld-linux-x86-64.so.2), notls, becauselscalls shared C library functions whose runtime addresses must be wired up first:execve("/usr/bin/ls", ["ls", "--color=auto", "-l"], ...) = 0 openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 mmap(NULL, ..., PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f8a... openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libselinux.so.1", O_RDONLY|O_CLOEXEC) = 3 mmap(...) # maps shared code (read+exec) and private data segments openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 mmap(...) mprotect(..., PROT_READ) # RELRO: locks the Global Offset Table read-only arch_prctl(ARCH_SET_FS, ...) # initializes thread-local storage (errno, etc.)ld.soinspectsls'sDT_NEEDEDtags (libc.so.6, pluslibselinux.so.1on many distros), looks up their paths in/etc/ld.so.cache(a binary index built byldconfig), andmmap()s each shared library into virtual memory (physical RAM pages for.textcode are shared across every running process on the machine).ld.soperforms relocations, fillingls's GOT (Global Offset Table) with resolved function pointers and marking it read-only viamprotect(RELRO hardening against memory-corruption exploits), sets up thread-local storage (errno), runs library initializers, and jumps tols'sAT_ENTRY(_start -> __libc_start_main -> main()).- Inside
main(),lsinitializes locale formatting (setlocale), parses-land--color=auto, and callsisatty(1)(implemented asioctl(1, TCGETS, ...)): becausefd 1is/dev/pts/N,TCGETSsucceeds, tellinglsto emit ANSI color escape sequences.
Reading directory entries (getdents64) and metadata (statx)
lsnever reads raw disk blocks or ext4 structures directly. It talks to the kernel's VFS (Virtual File System) — a uniform abstraction layer acrossext4,XFS,NFS,tmpfs, and/proc:openat(AT_FDCWD, ".", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = 3 getdents64(3, /* 5 entries: ".", "..", "run.sh", "notes.md", "src" */, 32768) = 136 statx(AT_FDCWD, "run.sh", AT_SYMLINK_NOFOLLOW|..., STATX_BASIC_STATS, {...}) = 0 statx(AT_FDCWD, "notes.md", AT_SYMLINK_NOFOLLOW|..., STATX_BASIC_STATS, {...}) = 0 statx(AT_FDCWD, "src", AT_SYMLINK_NOFOLLOW|..., STATX_BASIC_STATS, {...}) = 0 getdents64(3, /* 0 entries */, 32768) = 0 close(3) = 0- Enumerating names (
openat+getdents64):opendir(".")opens"."withO_DIRECTORY(fd = 3), andreaddir()callsgetdents64(3, buf, 32768)to fetch packed variable-lengthlinux_dirent64records (8-byte inode + 8-byte offset + 2-byte record length + 1-byte file type = 19-byte header, plus filename characters, plus1NUL byte, padded up to an 8-byte boundary).- Worked byte math: for
.(1 char ->20+1-> 24 B),..(2 chars ->20+2-> 24 B),run.sh(6 chars ->20+6-> 32 B),notes.md(8 chars ->20+8-> 32 B), andsrc(3 chars ->20+3-> 24 B),getdents64returns24 + 24 + 32 + 32 + 24 = 136bytes in a single syscall! A second call returns0(end of directory).
- Worked byte math: for
- Fetching
-lmetadata (statx):getdents64only gives names, inode numbers, and basic file types — not permissions, owners, byte sizes, or timestamps. Because-awas not given,lsignores.and..and issues onestatx()(ornewfstatat()) syscall per visible entry withAT_SYMLINK_NOFOLLOW(so symbolic links describe the link itself rather than following it;readlink()fetches"-> target"). The kernel serves these from its in-RAM dentry cache and inode cache, sleeping on block I/O only on a cold cache miss. - Formatting and the
totalheader:lsmaps numericuid/gidvalues to names via NSS (/etc/nsswitch.conf->/etc/passwdand/etc/group, cached in memory), checks extended attributes (lgetxattr) for SELinux.or POSIX ACL+markers, sorts entries using locale-awarestrcoll(), and sumsst_blocks(always counted in 512-byte units). Ifnotes.mdoccupies two 4 KiB blocks (st_blocks = 16) whilerun.shandsrceach occupy one 4 KiB block (st_blocks = 8),(16 + 8 + 8) × 512 = 16,384 bytes = 16 KiB, printed at the top astotal 16.
- Enumerating names (
Writing through the pty, exiting, and reaping the zombie
- Terminal output path (
write->pty): C's standard I/O library (stdio) configuresstdoutas line-buffered whenisatty(1)is true (flushing on every\n) and fully buffered (flushing in 4–8 KiB chunks) when writing to a pipe or file. On a terminal,ls -lissues 4write(1, ...)calls (total 16\nplus 3 file lines). Inside the kernel, theN_TTYline discipline converts\ninto\r\n(ONLCR) and places the bytes into theptymaster buffer, waking the terminal emulator (poll/read) to interpret ANSI color codes (such as\x1b[01;34mfor bold blue directories) and render glyphs on your monitor. - Process termination (
exit_groupand zombie state): returning0frommain()runsatexithandlers (GNUlsflushes and closesstdoutexplicitly so write errors likeENOSPCon a full redirected disk still trigger a non-zero exit!) and invokesexit_group(0). The kernel closes remaining file descriptors, frees all virtual memory mappings, retains a tiny zombie process-table record holding the PID, exit status, and CPU usage counters, and sendsSIGCHLDto parentbash. - Reaping and printing the next prompt (
wait4):bash, which has been sleeping inwait4()(the Linux syscall backingwaitpid()), wakes up, reads exit status0into$?, and destroys the zombie entry. Finally,bashreclaims foreground ownership of/dev/pts/Nviatcsetpgrp(), switches Readline back into non-canonical mode, writes the next interactive prompt (PS1) tostderr(fd 2), and blocks once again inread(0, ...)waiting for your next command.
- Terminal output path (
Intuition & how it works
Picture bash as a restaurant dispatcher standing at a pass-through service window called a pseudoterminal (pty) — a virtual two-way channel connecting your graphical terminal app on one side to shell programs on the other. When you type ls -l and press Return, bash does not list files itself: it translates any shorthand on your order slip, looks up where the /usr/bin/ls tool lives on the shelf (PATH), hires a temporary helper process (fork), hands that helper the ls program (execve), waits while ls asks the Linux kernel's Virtual File System (VFS) for directory names and permissions, watches the formatted lines slide back through the window (write), and signs off the helper's exit sheet (wait4) before asking for your next command.
Beginners often assume ls is baked directly into the shell or the Linux kernel, or imagine that ls reads raw disk sectors and paints colored letters onto the monitor. That mental model misses why Unix is so composable: ls is an ordinary unprivileged user-space binary that speaks only through standard system calls (controlled CPU transitions from unprivileged user space into privileged kernel space) and integer file descriptors (0 = input, 1 = output, 2 = error), allowing the exact same /usr/bin/ls binary to work over local windows, SSH sessions, output files, and multi-stage pipelines without changing a single line of ls code.
Trace running ls -l inside a folder holding 3 items (run.sh, notes.md, and subfolder src):
- Read & resolve: Readline inside
bashreads"ls -l\r"from/dev/pts/0, expandsalias ls='ls --color=auto', and checks$PATHdirectories vianewfstatat()until/usr/bin/lsmatches. - Spawn & link:
bashclones itself viaclone()(fork), puts the child in the foreground terminal group (setpgid+tcsetpgrp), and callsexecve("/usr/bin/ls", ...); the kernel maps the ELF (Linux executable format) segments lazily, and the dynamic linker (ld.so) mapslibc.so.6before callingmain(). - Query, print & reap:
lscallsopenat(".")andgetdents64()(receiving 5 packed records:.,..,run.sh,notes.md,src=136bytes), skips.and.., runs 3statx()calls totaling16 KiBof allocated blocks, writes 4 lines (total 16plus 3 rows) tofd 1for the terminal emulator to draw, and callsexit_group(0)sobash'swait4()can reap it and print the next prompt.
Key points
- Three-party terminal I/O: keystrokes travel from the terminal emulator ->
ptymaster -> kernelN_TTYline discipline (the kernel module handling terminal echoing, line buffering, andCtrl-Csignals) ->bash(GNU Readlinein non-canonical mode), and Readline restores standard terminal settings before launching the child. - User-space parsing and
$PATHlookup: the shell — never the kernel — expands aliases and*globs, checks shell functions and builtins (commands likecdthat must mutate the shell's own process state), and walks$PATH(127if missing,126if non-executable), caching hits in an internal hash table. - Two-step
fork+execvedesign: separating process cloning (fork/clone) from program loading (execve) gives the shell a clean window in the child to set foreground job-control groups (tcsetpgrp), reset ignored signals, and rewire file descriptors (dup2) while keeping the parent shell untouched. - Demand-paged ELF loading and
ld.so:execvesets up lazy virtual-memory mappings (faulted in from the kernel page cache on touch) and startsld.so, which maps shared.solibraries via/etc/ld.so.cache, resolves GOT (Global Offset Table) symbol pointers, locks them read-only (RELRO), and hands off tomain(). - VFS directory syscalls (
openat+getdents64+statx):lsenumerates filenames in bulk viagetdents64and fetches-lpermissions, sizes, and block counts viastatx(..., AT_SYMLINK_NOFOLLOW)backed by the kernel's in-RAM dentry and inode caches. - Clean exit and zombie reaping:
exit_group()frees memory and fds but leaves a tiny zombie record holding the exit code until parentbashreaps it viawait4(), updates$?, reclaims the foreground terminal, and printsPS1tostderr.
Common mistakes
- Claiming the kernel searches
$PATHor expands*.log:execverequires an explicit file path, and glob patterns like*are expanded into argument lists bybashin user space beforelsstarts. - Saying
fork()copies all ofbash's RAM: Linux uses Copy-on-Write (CoW), copying only page-table metadata and sharing physical RAM frames read-only until either process writes to a page. - Saying
lsreads disk blocks directly: user-space tools have no raw disk access;lsqueries the kernel VFS viagetdents64andstatx. - Forgetting
ld.sobeforemain(): dynamically linked binaries start inside the dynamic linker (PT_INTERP), not directly atls'smain(). - Skipping foreground process groups (
tcsetpgrp): without movinglsinto the terminal's foreground group, pressingCtrl-Cduring a slowlswould sendSIGINTtobashinstead ofls. - Forgetting zombie reaping (
waitpid/wait4): until the parent reads the child's exit status, a terminated child remains a zombie entry in the kernel process table.
Follow-up questions
- When an alias expands
lstols --color=auto, how does the binary decide whether to emit ANSI color codes viaisatty()? During tokenization,bashperforms plain text substitution on the first word, turningls -lintols --color=auto -l. Under--color=auto,lscallsisatty(1)— aglibchelper that issuesioctl(1, TCGETS)to check whether file descriptor1(stdout) refers to an interactive terminal device. When writing to/dev/pts/N,TCGETSsucceeds andlswraps filenames in ANSI escape codes (like\x1b[01;34mfor bold blue directories) and uses line-buffered output; when piped (ls | grep log) or redirected (ls > listing.txt),TCGETSfails withENOTTY, solsautomatically suppresses escape codes and switches to a 4–8 KiB block buffer so downstream tools receive clean plain text. - What problem does Copy-on-Write solve inside
fork(), and when arevfork()orposix_spawn()preferable? Duplicating a parent process's physical RAM only to discard it microseconds later atexecve()would waste huge amounts of CPU time and memory bandwidth, so Copy-on-Write (CoW) duplicates only the virtual page tables (address-translation maps) and marks private pages read-only, copying an individual 4 KiB page only if a write triggers a page fault. Even so, copying page tables still scales with parent size — an 8 GiB process has2,097,152pages (~16 MiB of page-table entries) and can failfork()withENOMEMwhen strict memory overcommit is enabled.vfork()avoids copying page tables altogether by letting the child briefly borrow the parent's address space while suspending the parent untilexecve()or_exit(), andposix_spawn()wraps that fastclone(CLONE_VM | CLONE_VFORK)path inside a safe declarative API for file redirections and signal masks (used by modern shells likefishandksh93as well as large runtimes like the JVM). - How do file descriptors and kernel synchronization change when piping output into a second process such as
ls | grep log? Before forking,bashcallspipe()(orpipe2()), creating a 64 KiB in-kernel ring buffer with two descriptors[read_fd, write_fd], then forks twice into a single shared job process group: the left child (ls) callsdup2(write_fd, 1)to routestdoutinto the pipe, the right child (grep) callsdup2(read_fd, 0)to readstdinfrom the pipe, and all three processes (ls,grep, and parentbash) close their unused copies ofread_fdandwrite_fdsogrepwill actually see end-of-file (readreturning0) oncelsexits. Both children run concurrently and the kernel synchronizes them automatically:grepsleeps inread()whenever the buffer is empty,lssleeps inwrite()whenever the 64 KiB buffer is full (backpressure), and ifgrepexits early (for examplegrep -m 1),ls's nextwrite()receivesSIGPIPEto terminate cleanly whilebashcallswaitpid()for both children.
Follow-up questions
- When an alias expands `ls` to `ls --color=auto`, how does the binary decide whether to emit ANSI color codes via `isatty()`?
- What problem does Copy-on-Write solve inside `fork()`, and when are `vfork()` or `posix_spawn()` preferable?
- How do file descriptors and kernel synchronization change when piping output into a second process such as `ls | grep log`?
Similar questions
- Contrasting Linux Containers with Hardware Virtualization
- Expected Passenger Wait Across Repeating Transit Headways
- Mechanics and Trade-Offs of SGD vs. Adam
- Arithmetic Square Root and In-Place Parity Partitioning
- Largest Manhattan Distance Across Matched Slices
- Mentoring a Student on Indexing or Async Execution
More Deshaw interview questions
- Contrasting Linux Containers with Hardware Virtualization Medium
- Expected Passenger Wait Across Repeating Transit Headways Hard
- Mechanics and Trade-Offs of SGD vs. Adam Hard Pro
- Arithmetic Square Root and In-Place Parity Partitioning Medium Pro
- Largest Manhattan Distance Across Matched Slices Medium Pro
- Mentoring a Student on Indexing or Async Execution Medium Pro