Skip to main content
Cloud, DevOps & Systems

Linux Interview Questions

All Levels (Junior to Staff)16 Questions

Linux systems engineering: kernel process scheduling, memory virtual addressing, file descriptors, signals, cgroups, systemd, and strace/tcpdump diagnostics.

24 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Linux Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How do inodes, directory entries, hard links, and symbolic links work in a Linux filesystem?

Senior Engineering Answer

An inode is a filesystem metadata structure storing file size, owner, permissions, timestamps, and pointers to disk data blocks—but NOT the filename. Directory entries map human-readable filenames to inode numbers. A hard link creates another directory entry pointing to the same inode (incrementing its link count); data persists until the link count reaches zero AND all open file descriptors close. A symbolic link is a separate inode containing a text path string that breaks if the target moves or is deleted.

Production Code Example
ls -li app.log
ln app.log app.hard.log       # Same inode number, link count becomes 2
ln -s /var/log/app.log link.log  # Different inode, points to pathname
Common Interview Trap / Anti-Pattern:

Deleting a massive open log file with rm frees the directory name immediately, but disk space stays occupied (shown by df vs du discrepancies) until the daemon holding the open file descriptor closes it or rotates logs.

Question #2FundamentalJunior

What is the difference between a process, a thread, and Linux process states (R, S, D, Z, T)?

Senior Engineering Answer

In the Linux kernel, both processes and threads are represented as task_struct entries created via clone(); processes isolate virtual memory, file tables, and signal handlers, whereas threads within a process share the same virtual address space and file descriptor table. Process states include R (running/runnable), S (interruptible sleep waiting for an event), D (uninterruptible sleep blocked on kernel disk/NFS I/O), Z (zombie awaiting parent waitpid()), and T (stopped by SIGSTOP or debugger).

Production Code Example
ps -eo pid,ppid,stat,comm --sort=-pcpu | head -n 15
Common Interview Trap / Anti-Pattern:

Attempting to kill a D-state process with kill -9 (SIGKILL) has no effect because the process will not handle pending signals until the underlying blocked kernel I/O syscall returns.

Question #3FundamentalJunior

How do Unix file permissions, special bits (setuid, setgid, sticky bit), and umask work?

Senior Engineering Answer

Standard permissions grant read (4), write (2), and execute (1) for user, group, and others; on directories, execute (x) grants traversal access. Special bits add setuid (4000: run binary with owner's EUID, e.g., /usr/bin/passwd), setgid (2000: on directories, new files inherit parent group), and the sticky bit (1000: on shared directories like /tmp, only file owners or root can delete files inside). umask subtracts default permission bits when new files/directories are created.

Production Code Example
chmod 1777 /shared/tmp   # Sticky bit enabled
umask 027                # New files 640 (rw-r-----), new dirs 750 (rwxr-x---)
Common Interview Trap / Anti-Pattern:

Granting read (r) without execute (x) on a directory lets users list filenames via ls, but fails with Permission Denied when accessing or stat-ing any file inside.

Question #4FundamentalJunior

How do stdin, stdout, stderr, pipes, and exit codes compose in shell pipelines?

Senior Engineering Answer

Every Linux process opens three standard file descriptors by default: 0 (stdin), 1 (stdout), and 2 (stderr). Pipes (|) connect stdout (FD 1) of the left command directly to stdin (FD 0) of the right command using an in-memory kernel pipe buffer, leaving stderr free for error messages unless redirected with 2>&1. Commands return an 8-bit exit status (0 for success, non-zero for failure); in Bash pipelines, only the last command's exit status is returned unless set -o pipefail is enabled.

Production Code Example
# Redirect stdout and stderr to log while preserving exit code failure detection
set -euo pipefail
./build.sh > build.log 2>&1
Common Interview Trap / Anti-Pattern:

Writing cmd 2>&1 > out.log instead of cmd > out.log 2>&1 redirects stderr to the terminal BEFORE stdout is redirected to out.log because redirections evaluate left-to-right.

Question #5IntermediateMid-Level

How do Virtual Memory, the Page Cache, copy-on-write fork(), and free -h 'available' memory work?

Senior Engineering Answer

Linux maps process virtual addresses through multi-level page tables and the CPU MMU/TLB to physical RAM frames lazily (demand paging—pages are only backed by physical RAM when touched). Unused RAM is opportunistically filled by the kernel Page Cache to buffer disk reads and writes in memory; 'available' in free -h counts free RAM plus cleanly reclaimable page cache. During fork(), parent and child share physical pages marked read-only via copy-on-write (COW), duplicating a 4 KB page only when either process modifies it.

Production Code Example
free -h
# Inspect detailed page cache, dirty pages awaiting disk flush, and slab usage
grep -E 'MemAvailable|Cached|Dirty|Slab' /proc/meminfo
Common Interview Trap / Anti-Pattern:

Misreading low 'free' memory in free -h or top as a RAM shortage when 80% of RAM is actually healthy, instantly reclaimable Page Cache reported under 'available'.

Question #6IntermediateMid-Level

How do Linux signals (SIGTERM, SIGINT, SIGKILL, SIGHUP, SIGCHLD) work, and why can SIGKILL never be caught?

Senior Engineering Answer

Signals are asynchronous kernel notifications delivered to processes. SIGINT (Ctrl+C), SIGTERM (graceful shutdown request), and SIGHUP (reload config or hangup) can be caught via sigaction() handlers so processes flush buffers and close sockets cleanly. SIGCHLD notifies a parent when a child exits so it can call waitpid() and prevent zombie accumulation. SIGKILL (9) and SIGSTOP (19) are handled strictly inside the kernel and cannot be caught, blocked, or ignored by user space.

Production Code Example
# Always try graceful SIGTERM before falling back to SIGKILL
kill -TERM $PID && sleep 5 && kill -0 $PID 2>/dev/null && kill -KILL $PID
Common Interview Trap / Anti-Pattern:

Running kill -9 as a first resort on databases or stateful queues skips fsync/flush handlers, leaving lockfiles behind and forcing lengthy crash recovery on startup.

Question #7IntermediateMid-Level

How do you trace system calls and diagnose hanging or failing binaries using strace, lsof, and ss?

Senior Engineering Answer

strace intercepts and prints every syscall (openat, connect, read, futex) and signal made by a process, revealing missing config files (ENOENT), permission errors (EACCES), or hung network/mutex waits without needing source code or debug symbols. lsof lists open files, deleted-but-open unlinked descriptors, and sockets held by processes. ss replaces legacy netstat by querying kernel netlink sockets directly to show TCP states, send/recv queues, and owning processes in O(1) kernel sweeps.

Production Code Example
strace -f -e trace=file,network -p $PID
ss -tunapl state established '( dport = :5432 or sport = :5432 )'
lsof +L1    # Find deleted files still held open by processes
Common Interview Trap / Anti-Pattern:

Attaching strace without filtering (-e trace=...) to a high-throughput production service pauses the target process on every syscall entry and exit, degrading throughput by 10x-100x.

Question #8IntermediateMid-Level

How does systemd manage service lifecycles, socket activation, resource limits (cgroups v2), and journald logs?

Senior Engineering Answer

systemd acts as PID 1, executing declarative .service units organized in a dependency DAG rather than serial SysV init scripts. Every service runs inside its own cgroup v2 slice, enforcing directives like MemoryMax, CPUQuota, and Restart=on-failure. Socket activation (.socket units) lets systemd bind listening ports early and spawn the daemon on first connection, enabling zero-dropped-packet restarts. Standard streams flow automatically to journald for structured querying via journalctl.

Production Code Example
# /etc/systemd/system/worker.service
[Service]
ExecStart=/usr/local/bin/worker
Restart=always
MemoryMax=1G
CPUQuota=200%

# Query logs since last hour:
# journalctl -u worker.service --since "1 hour ago" -p err
Common Interview Trap / Anti-Pattern:

Using Type=simple when a daemon forks into the background (daemonizes) tricks systemd into thinking the service exited immediately and triggers an endless restart loop.

Question #9AdvancedSenior

How does epoll achieve O(1) I/O multiplexing compared to select and poll for high-concurrency network servers?

Senior Engineering Answer

select and poll require user space to pass the entire array of watched file descriptors into the kernel on every call, forcing the kernel to scan O(N) descriptors each iteration (plus select's fixed FD_SETSIZE=1024 cap). epoll creates an in-kernel red-black tree via epoll_create1() and registers sockets once with epoll_ctl(). Kernel socket callbacks push only active ready descriptors onto a ready list, so epoll_wait() returns O(ready events) regardless of having 100,000+ idle connections. Edge-triggered mode (EPOLLET) notifies only on state transitions and requires non-blocking read/write loops until EAGAIN.

Production Code Example
// Edge-triggered epoll requires draining socket until EAGAIN
while ((n = read(fd, buf, sizeof(buf))) > 0) {
    process(buf, n);
}
if (n == -1 && errno != EAGAIN && errno != EWOULDBLOCK) {
    close(fd);
}
Common Interview Trap / Anti-Pattern:

Using edge-triggered epoll (EPOLLET) without looping until EAGAIN stalls remaining buffered bytes in the kernel socket queue indefinitely because no new arrival edge fires.

Question #10AdvancedSenior

How do Linux Load Average numbers work, and why can load average spike even when CPU utilization is low?

Senior Engineering Answer

Linux load averages (1, 5, and 15-minute exponentially damped moving averages) measure the average number of tasks in either runnable state (R, waiting for or executing on CPU) OR uninterruptible sleep state (D, blocked on disk/NFS I/O). Unlike other Unix systems, Linux includes D-state tasks in load average—so a 4-core server can report a load average of 50 with 5% CPU usage when threads stall waiting on slow NVMe storage or an unresponsive NFS mount.

Production Code Example
uptime
vmstat 1 5   # Compare 'r' (runnable) vs 'b' (blocked in uninterruptible sleep) and 'wa' (iowait)
Common Interview Trap / Anti-Pattern:

Scaling CPU cores solely because load average exceeds core count without checking vmstat/iostat wastes budget when the bottleneck is actually storage I/O or lock contention.

Question #11AdvancedSenior

How does the Linux OOM Killer select a process to terminate, and how does cgroups v2 memory.high differ from memory.max?

Senior Engineering Answer

When physical RAM and swap are exhausted (or a cgroup breaches memory.max), the kernel invokes the OOM Killer, computing each process's badness score from its RSS/swap footprint adjusted by /proc/<pid>/oom_score_adj (-1000 immune to +1000 kill first). In cgroups v2, setting memory.high sets a soft throttle limit: crossing it forces direct memory reclamation and slows allocations down cleanly before hitting memory.max's hard OOM kill—and systemd-oomd can act proactively via PSI (Pressure Stall Information) metrics before thrashing locks up the node.

Production Code Example
cat /proc/$(pgrep postgres)/oom_score
cat /proc/pressure/memory   # PSI metrics: avg10/avg60 stall percentages
Common Interview Trap / Anti-Pattern:

Setting vm.overcommit_memory=0 (heuristic) on database hosts with large fork() operations or disabled swap can still trigger host-wide OOM kills if RSS surges unexpectedly.

Question #12AdvancedSenior

How does the Linux kernel TCP handshake, SYN backlog, TIME_WAIT state, and sysctl tuning handle high connection churn?

Senior Engineering Answer

Incoming TCP SYNs enter the SYN queue (sized by net.ipv4.tcp_max_syn_backlog) until the ACK arrives and moves the socket to the accept queue (capped by min(listen() backlog, net.core.somaxconn)). If an application falls behind on accept(), SYN packets drop or trigger SYN cookies. After closing, the side initiating active close holds the socket in TIME_WAIT for 2*MSL (60s in Linux) to catch delayed duplicate packets. Enabling net.ipv4.tcp_tw_reuse allows safe reuse of TIME_WAIT sockets for outbound connections when TCP timestamps are active.

Production Code Example
sysctl net.core.somaxconn net.ipv4.tcp_max_syn_backlog net.ipv4.ip_local_port_range
nstat -az TcpExtListenOverflows TcpExtListenDrops
Common Interview Trap / Anti-Pattern:

Enabling legacy tcp_tw_recycle (removed in Linux 4.12) breaks clients behind corporate NATs; always diagnose ephemeral port exhaustion and somaxconn listen overflows with nstat instead.

Question #13StaffPrincipal / Staff

How do perf, eBPF, and flame graphs diagnose CPU hotspots and off-CPU scheduler latency in production?

Senior Engineering Answer

perf record samples hardware PMU counters (cycles, cache-misses, branch-misses) and call stacks at fixed frequencies (e.g., 99 Hz to avoid lockstep aliasing with 100 Hz timers) to build on-CPU flame graphs where horizontal width shows total CPU time spent in each stack frame. For threads spending most of their latency blocked on futexes, disk I/O, or scheduler runqueues rather than burning CPU, eBPF tools (bpftrace, BCC offcputime, runqlat) trace kernel kprobes/tracepoints in-kernel with near-zero overhead.

Production Code Example
# Sample cluster-wide CPU stacks for 30s at 99 Hz with DWARF unwinding
perf record -F 99 -a -g --call-graph dwarf -- sleep 30
# Trace kernel scheduler runqueue latency via bpftrace
bpftrace -e 'tracepoint:sched:sched_wakeup { @q[args->pid] = nsecs; }'
Common Interview Trap / Anti-Pattern:

Using on-CPU perf flame graphs to debug slow endpoints whose threads are actually sleeping on downstream locks or DNS timeouts shows almost nothing useful—use off-CPU eBPF tracing instead.

Question #14StaffPrincipal / Staff

How does io_uring achieve zero-copy/low-syscall asynchronous I/O compared to POSIX AIO and blocking syscalls?

Senior Engineering Answer

Traditional async disk I/O in Linux suffered from POSIX AIO user-space thread pools or O_DIRECT alignment constraints. io_uring creates two lockless ring buffers shared directly via mmap between user space and the kernel: a Submission Queue (SQ) and a Completion Queue (CQ). Applications batch dozens of file/socket reads, writes, or accepts into the SQ and submit/reap with minimal (or zero, under SQPOLL kernel polling mode) syscall transitions, avoiding Spectre/Meltdown syscall mitigation overhead and context-switch penalties.

Production Code Example
// Conceptual io_uring flow: user space writes SQEs -> shared ring -> kernel processes -> writes CQEs
struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
io_uring_prep_read(sqe, fd, buf, len, offset);
io_uring_submit(&ring);
Common Interview Trap / Anti-Pattern:

Exposing unrestricted io_uring inside multi-tenant containers without seccomp filtering has historically widened kernel attack surface because io_uring bypasses many standard per-syscall seccomp hooks.

Question #15StaffPrincipal / Staff

How do Linux kernel page cache dirty-writeback ratios (vm.dirty_ratio / dirty_background_ratio) cause sudden latency stalls?

Senior Engineering Answer

Buffered writes return immediately after copying bytes into the Page Cache and marking pages dirty. Background kernel flusher threads wake up once dirty pages hit vm.dirty_background_ratio (or dirty_background_bytes) to flush asynchronously. If write speed exceeds disk throughput and dirty memory reaches vm.dirty_ratio (default 20% of RAM—tens of gigabytes on modern 256 GB servers!), the kernel synchronously blocks application write() syscalls until pages flush to disk, causing multi-second p99 latency spikes.

Production Code Example
sysctl -w vm.dirty_background_bytes=67108864  # 64 MB
sysctl -w vm.dirty_bytes=536870912            # 512 MB cap prevents multi-GB flush stalls
Common Interview Trap / Anti-Pattern:

Leaving percentage-based dirty_ratio defaults on large-RAM servers lets tens of gigabytes of dirty buffers accumulate before triggering massive sudden disk saturation pauses.

Question #16StaffPrincipal / Staff

How do NUMA architecture, CPU pinning, and IRQ affinity affect ultra-low-latency Linux workloads?

Senior Engineering Answer

On multi-socket servers, each CPU socket owns local DIMM memory controllers (NUMA nodes). Accessing RAM attached to a remote socket traverses the UPI/Infinity Fabric interconnect, adding memory latency and bandwidth contention. High-throughput databases and packet processors bind processes to a single NUMA node with numactl --cpunodebind --membind (and tune vm.zone_reclaim_mode=0 to avoid premature local reclaim), while pinning NIC RX/TX interrupts (/proc/irq/*/smp_affinity) to cores on the same socket as the PCIe NIC.

Production Code Example
numactl --hardware
numactl --cpunodebind=0 --membind=0 ./high-freq-engine
Common Interview Trap / Anti-Pattern:

Allocating all memory on NUMA node 0 during initialization and letting the scheduler migrate threads onto node 1 creates severe cross-socket memory stalls under load.

Linux Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Linux preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Cloud, DevOps & Systems.

JuniorFundamental

How do inodes, directory entries, hard links, and symbolic links work in a Linux filesystem?

JuniorFundamental

What is the difference between a process, a thread, and Linux process states (R, S, D, Z, T)?

JuniorFundamental

How do Unix file permissions, special bits (setuid, setgid, sticky bit), and umask work?

JuniorFundamental

How do stdin, stdout, stderr, pipes, and exit codes compose in shell pipelines?

Mid-LevelIntermediate

How do Virtual Memory, the Page Cache, copy-on-write fork(), and free -h 'available' memory work?

Mid-LevelIntermediate

How do Linux signals (SIGTERM, SIGINT, SIGKILL, SIGHUP, SIGCHLD) work, and why can SIGKILL never be caught?

Frequently Asked Technical Interview Questions (Linux)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

What is the difference between a soft limit and a hard limit in ulimit (/etc/security/limits.conf)?
A soft limit (such as open file descriptors nofile) is the active runtime threshold enforced by the kernel; an unprivileged process can raise its own soft limit up to the hard limit. Only a privileged process (root or CAP_SYS_RESOURCE) can raise a hard limit.
How do /proc and /sys filesystems differ in Linux?
/proc (procfs) exposes live kernel process trees (/proc/<pid>/fd, maps, status) and system runtime metrics/tunables (/proc/meminfo, /proc/sys). /sys (sysfs) provides a structured hierarchical model of kernel devices, drivers, block hardware, and cgroup v2 controls (/sys/fs/cgroup).
Why does Linux use Swap even when free RAM still exists, and what does vm.swappiness control?
Linux swaps out cold, rarely accessed anonymous memory pages (like idle daemon initialization blocks) to free physical RAM for valuable active Page Cache. vm.swappiness (0-200, default 60) biases how aggressively the kernel prefers swapping anonymous pages versus reclaiming file-backed page cache.
How do iptables and nftables differ from eBPF/XDP for Linux packet filtering?
iptables evaluates linear rule chains inside Netfilter hooks. nftables replaces iptables with a single kernel VM, atomic rule updates, and fast sets/maps. XDP (eXpress Data Path) attaches eBPF programs directly in the NIC driver's RX ring buffer BEFORE the kernel allocates an sk_buff structure, enabling tens of millions of DDoS packet drops per core.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks