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:

  1. 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.
  2. Executable discovery: How the shell locates the ls program on disk using its command cache and PATH directories.
  3. Spawning and loading the binary: Which system calls (fork/clone plus execve, or vfork/posix_spawn) create the child process, preserve or rewire standard descriptors (0, 1, 2), and map the ELF image into virtual memory.
  4. Shared-library linking and C startup: How ld.so maps required shared objects (such as libc.so) and resolves symbols prior to invoking main().
  5. Enumerating entries and querying attributes: Which kernel Virtual File System (VFS) calls ls makes to read filenames (getdents64) and retrieve -l metadata (statx or newfstatat).
  6. 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

  1. Keystrokes, pseudoterminals, and kernel transitions

    Before ls even 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 (or sshd over 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 by bash as file descriptors (integer handles into the process's open-file table) 0 (stdin), 1 (stdout), and 2 (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_TTY runs in canonical mode (ICANON + ECHO), meaning the kernel buffers characters, handles Backspace itself, echoes letters back to the screen, and wakes read() only when a newline arrives. However, interactive bash uses GNU Readline (to support arrow keys, command history, and Tab completion): before printing your prompt, Readline calls tcsetattr() (ioctl(0, TCSETS, ...)) to disable ICANON and ECHO so bash wakes on every keystroke via read(0, buf, 1) and echoes characters itself. (ISIG remains enabled so Ctrl-C makes the kernel send SIGINT to the foreground process group.)
    • How a system call crosses into the kernel: each read() wrapper in glibc places syscall number 0 (SYS_read) into register rax, executes the x86-64 syscall instruction to jump into ring 0 on a kernel stack, sleeps on a kernel wait queue while you think (consuming 0% CPU), and returns via sysret once 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" to bash's parser.
  2. Tokenizing, expansions, aliases, and command classification

    The Linux kernel has no idea what shell syntax, quotes, or * wildcards mean — bash parses and transforms the command line entirely in user space:

    1. Tokenizing and alias substitution: bash splits "ls -l" into tokens around unquoted whitespace. Because this is an interactive shell, bash checks whether the first word matches an alias (a pure text macro). Most Linux distributions define alias ls='ls --color=auto' in ~/.bashrc, transforming the words into ["ls", "--color=auto", "-l"].
    2. Shell expansions (in strict order): brace expansion ({a,b}) -> tilde (~), variable ($HOME), arithmetic, and command substitution ($(...)) -> word splitting -> pathname (glob) expansion -> quote removal. For ls -l, nothing changes; if you had typed ls -l *.log, bash itself would scan the current directory and replace *.log with ["app.log", "db.log"] before launching ls (ls never sees the * character). Any redirections like > listing.txt are stripped out to be wired up later in the child.
    3. Command classification: for a command name containing no / slash, bash checks in order:
      • Shell function -> Shell builtin (like cd, export, or ulimit, which must execute directly inside the bash process without spawning a child, because a child process cannot modify its parent's working directory or environment variables) -> External executable.
    $ type -a ls
    ls is aliased to `ls --color=auto'
    ls is /usr/bin/ls
    ls is /bin/ls
    

    (On modern merged-/usr Linux distributions, /bin is a symbolic link to /usr/bin.)

  3. Resolving /usr/bin/ls via the hash cache and PATH

    Because ls is neither a function nor a builtin, and "ls" contains no /, bash must locate the executable file in user space:

    • Internal hash table first: bash keeps an in-memory dictionary mapping previously run command names to their resolved paths (viewable with hash). On a cache hit, bash skips directory probing completely.
    • Walking $PATH on a first run: bash reads its PATH environment 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 via newfstatat() (or stat()) 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 PATH directory misses, bash prints command not found and sets exit status 127; if a matching file exists without execute permissions, exit status is 126.

  4. 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 by execve() (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 modern glibc, calling fork() invokes the Linux clone() 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 fds 0, 1, and 2 still 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 parent bash, 0 in the child.
    • Foreground job control and signals: both parent and child call setpgid() to put the child in its own process group, and tcsetpgrp() (ioctl TIOCSPGRP) makes that group the terminal's foreground group so Ctrl-C (SIGINT) or Ctrl-Z (SIGTSTP) targets ls instead of killing bash. The child also resets signal handlers ignored by interactive bash (SIGQUIT, SIGTSTP) back to SIG_DFL and applies any I/O redirections (open + dup2 + close).
    • Loading the ELF binary (execve): the child calls execve("/usr/bin/ls", ["ls", "--color=auto", "-l"], envp). Inside the kernel:
      1. Verifies execute permissions and inspects the file's magic header bytes (\x7fELF selects the ELF — Executable and Linkable Format — binary loader; #! would recursively invoke an interpreter script).
      2. Discards the inherited bash virtual memory mappings (the point of no return) while preserving PID, working directory, and open descriptors not marked O_CLOEXEC.
      3. Sets up lazy virtual memory mappings (mmap) for ls's PT_LOAD code 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).
      4. Reads the PT_INTERP header (/lib64/ld-linux-x86-64.so.2), maps that dynamic linker into memory, builds the initial user stack (argc, argv pointers, envp pointers, and the auxiliary vector passing kernel metadata like page size AT_PAGESZ, ls's real entry point AT_ENTRY, and the vDSO fast clock/gettimeofday page), and jumps to ld.so's entry point on return to user space.

    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)
    
  5. 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), not ls, because ls calls 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.)
    
    1. ld.so inspects ls's DT_NEEDED tags (libc.so.6, plus libselinux.so.1 on many distros), looks up their paths in /etc/ld.so.cache (a binary index built by ldconfig), and mmap()s each shared library into virtual memory (physical RAM pages for .text code are shared across every running process on the machine).
    2. ld.so performs relocations, filling ls's GOT (Global Offset Table) with resolved function pointers and marking it read-only via mprotect (RELRO hardening against memory-corruption exploits), sets up thread-local storage (errno), runs library initializers, and jumps to ls's AT_ENTRY (_start -> __libc_start_main -> main()).
    3. Inside main(), ls initializes locale formatting (setlocale), parses -l and --color=auto, and calls isatty(1) (implemented as ioctl(1, TCGETS, ...)): because fd 1 is /dev/pts/N, TCGETS succeeds, telling ls to emit ANSI color escape sequences.
  6. Reading directory entries (getdents64) and metadata (statx)

    ls never reads raw disk blocks or ext4 structures directly. It talks to the kernel's VFS (Virtual File System) — a uniform abstraction layer across ext4, 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 "." with O_DIRECTORY (fd = 3), and readdir() calls getdents64(3, buf, 32768) to fetch packed variable-length linux_dirent64 records (8-byte inode + 8-byte offset + 2-byte record length + 1-byte file type = 19-byte header, plus filename characters, plus 1 NUL 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), and src (3 chars -> 20+3 -> 24 B), getdents64 returns 24 + 24 + 32 + 32 + 24 = 136 bytes in a single syscall! A second call returns 0 (end of directory).
    • Fetching -l metadata (statx): getdents64 only gives names, inode numbers, and basic file types — not permissions, owners, byte sizes, or timestamps. Because -a was not given, ls ignores . and .. and issues one statx() (or newfstatat()) syscall per visible entry with AT_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 total header: ls maps numeric uid/gid values to names via NSS (/etc/nsswitch.conf -> /etc/passwd and /etc/group, cached in memory), checks extended attributes (lgetxattr) for SELinux . or POSIX ACL + markers, sorts entries using locale-aware strcoll(), and sums st_blocks (always counted in 512-byte units). If notes.md occupies two 4 KiB blocks (st_blocks = 16) while run.sh and src each occupy one 4 KiB block (st_blocks = 8), (16 + 8 + 8) × 512 = 16,384 bytes = 16 KiB, printed at the top as total 16.
  7. Writing through the pty, exiting, and reaping the zombie

    • Terminal output path (write -> pty): C's standard I/O library (stdio) configures stdout as line-buffered when isatty(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 -l issues 4 write(1, ...) calls (total 16\n plus 3 file lines). Inside the kernel, the N_TTY line discipline converts \n into \r\n (ONLCR) and places the bytes into the pty master buffer, waking the terminal emulator (poll/read) to interpret ANSI color codes (such as \x1b[01;34m for bold blue directories) and render glyphs on your monitor.
    • Process termination (exit_group and zombie state): returning 0 from main() runs atexit handlers (GNU ls flushes and closes stdout explicitly so write errors like ENOSPC on a full redirected disk still trigger a non-zero exit!) and invokes exit_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 sends SIGCHLD to parent bash.
    • Reaping and printing the next prompt (wait4): bash, which has been sleeping in wait4() (the Linux syscall backing waitpid()), wakes up, reads exit status 0 into $?, and destroys the zombie entry. Finally, bash reclaims foreground ownership of /dev/pts/N via tcsetpgrp(), switches Readline back into non-canonical mode, writes the next interactive prompt (PS1) to stderr (fd 2), and blocks once again in read(0, ...) waiting for your next command.

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):

  1. Read & resolve: Readline inside bash reads "ls -l\r" from /dev/pts/0, expands alias ls='ls --color=auto', and checks $PATH directories via newfstatat() until /usr/bin/ls matches.
  2. Spawn & link: bash clones itself via clone() (fork), puts the child in the foreground terminal group (setpgid + tcsetpgrp), and calls execve("/usr/bin/ls", ...); the kernel maps the ELF (Linux executable format) segments lazily, and the dynamic linker (ld.so) maps libc.so.6 before calling main().
  3. Query, print & reap: ls calls openat(".") and getdents64() (receiving 5 packed records: ., .., run.sh, notes.md, src = 136 bytes), skips . and .., runs 3 statx() calls totaling 16 KiB of allocated blocks, writes 4 lines (total 16 plus 3 rows) to fd 1 for the terminal emulator to draw, and calls exit_group(0) so bash's wait4() can reap it and print the next prompt.

Key points

  • Three-party terminal I/O: keystrokes travel from the terminal emulator -> pty master -> kernel N_TTY line discipline (the kernel module handling terminal echoing, line buffering, and Ctrl-C signals) -> bash (GNU Readline in non-canonical mode), and Readline restores standard terminal settings before launching the child.
  • User-space parsing and $PATH lookup: the shell — never the kernel — expands aliases and * globs, checks shell functions and builtins (commands like cd that must mutate the shell's own process state), and walks $PATH (127 if missing, 126 if non-executable), caching hits in an internal hash table.
  • Two-step fork + execve design: 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: execve sets up lazy virtual-memory mappings (faulted in from the kernel page cache on touch) and starts ld.so, which maps shared .so libraries via /etc/ld.so.cache, resolves GOT (Global Offset Table) symbol pointers, locks them read-only (RELRO), and hands off to main().
  • VFS directory syscalls (openat + getdents64 + statx): ls enumerates filenames in bulk via getdents64 and fetches -l permissions, sizes, and block counts via statx(..., 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 parent bash reaps it via wait4(), updates $?, reclaims the foreground terminal, and prints PS1 to stderr.

Common mistakes

  • Claiming the kernel searches $PATH or expands *.log: execve requires an explicit file path, and glob patterns like * are expanded into argument lists by bash in user space before ls starts.
  • Saying fork() copies all of bash'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 ls reads disk blocks directly: user-space tools have no raw disk access; ls queries the kernel VFS via getdents64 and statx.
  • Forgetting ld.so before main(): dynamically linked binaries start inside the dynamic linker (PT_INTERP), not directly at ls's main().
  • Skipping foreground process groups (tcsetpgrp): without moving ls into the terminal's foreground group, pressing Ctrl-C during a slow ls would send SIGINT to bash instead of ls.
  • 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 ls to ls --color=auto, how does the binary decide whether to emit ANSI color codes via isatty()? During tokenization, bash performs plain text substitution on the first word, turning ls -l into ls --color=auto -l. Under --color=auto, ls calls isatty(1) — a glibc helper that issues ioctl(1, TCGETS) to check whether file descriptor 1 (stdout) refers to an interactive terminal device. When writing to /dev/pts/N, TCGETS succeeds and ls wraps filenames in ANSI escape codes (like \x1b[01;34m for bold blue directories) and uses line-buffered output; when piped (ls | grep log) or redirected (ls > listing.txt), TCGETS fails with ENOTTY, so ls automatically 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 are vfork() or posix_spawn() preferable? Duplicating a parent process's physical RAM only to discard it microseconds later at execve() 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 has 2,097,152 pages (~16 MiB of page-table entries) and can fail fork() with ENOMEM when 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 until execve() or _exit(), and posix_spawn() wraps that fast clone(CLONE_VM | CLONE_VFORK) path inside a safe declarative API for file redirections and signal masks (used by modern shells like fish and ksh93 as 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, bash calls pipe() (or pipe2()), 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) calls dup2(write_fd, 1) to route stdout into the pipe, the right child (grep) calls dup2(read_fd, 0) to read stdin from the pipe, and all three processes (ls, grep, and parent bash) close their unused copies of read_fd and write_fd so grep will actually see end-of-file (read returning 0) once ls exits. Both children run concurrently and the kernel synchronizes them automatically: grep sleeps in read() whenever the buffer is empty, ls sleeps in write() whenever the 64 KiB buffer is full (backpressure), and if grep exits early (for example grep -m 1), ls's next write() receives SIGPIPE to terminate cleanly while bash calls waitpid() for both children.

Follow-up questions

Similar questions

More Deshaw interview questions

All 7 Deshaw questions →