System Calls & the Kernel Interface Questions
The boundary between user space and the kernel: how programs request privileged services through system calls, the user/kernel mode transition, and the semantics of core POSIX calls such as fork, exec, wait, open, read, write, and stat. Covers syscall numbers, arguments, return values and errno, and how libc wrappers relate to the underlying trap. This is the foundational interface for all systems programming on Unix/Linux.
You suspect a running process is leaking file descriptors and hitting EMFILE. Describe, step-by-step and with concrete commands, how you would locate and confirm the leak on a production Linux host without restarting the process. Include use of /proc/<pid>/fd, lsof, strace, and explain trade-offs between using strace vs eBPF/bpftrace for live systems.
Sample Answer
A process hitting EMFILE ("too many open files") is telling you it has exceeded its file descriptor limit; the goal is to confirm that's genuinely a leak (fds accumulating and never being closed) rather than a legitimately high but stable concurrency level, and to find what kind of descriptor is accumulating, all without restarting the process and losing the evidence.
1. Confirm the limit and the current count
cat /proc/<pid>/limits | grep 'Max open files' shows the soft/hard RLIMIT_NOFILE ceiling for that specific process (this can differ per-process even on the same host, depending on how it was launched). ls -la /proc/<pid>/fd | wc -l gives the current open-fd count; comparing the two tells you how close to EMFILE the process actually is right now, and repeating the count every few seconds (or under watch) shows whether it's climbing or holding steady.
2. Identify what's accumulating
ls -la /proc/<pid>/fd (without piping to wc) shows what each fd actually points at: a regular file path, socket:[inode], pipe:[inode], or anon_inode:[...]. A steadily growing list of socket:[...] entries with no corresponding drop in connection count elsewhere usually means sockets aren't being closed after use (a common bug: an exception path that skips a close() a normal-completion path reaches); a growing list of regular-file paths, especially many entries pointing at the same file or directory, points at a file-open-without-close bug instead. lsof -p <pid> gives the same information in a friendlier format, with the socket's remote address/port or the file's full path directly in the output, and lsof -p <pid> | awk '{print $5}' | sort | uniq -c | sort -rn gives a quick breakdown by fd type (REG, sock, DIR, etc.) if there's a large number of descriptors and eyeballing the raw list is impractical.
3. Confirm it against code paths with strace
strace -f -p <pid> -e trace=open,openat,socket,accept4,close -T (the -T flag shows time spent in each call) attached to the live process shows, in real time, which of open/openat/socket/accept4 calls are happening without a matching close; watching this for a short window while cross-referencing against the growing /proc/<pid>/fd listing usually pinpoints the exact operation (e.g. "accept4() calls without a corresponding close() on error paths") responsible.
4. strace vs. eBPF/bpftrace for live systems
strace attaches via ptrace(2), which stops the traced process at every intercepted syscall; this is simple and universally available, but the overhead is significant (each traced syscall pays for two stops and a context switch round-trip to the tracer) and can noticeably slow the very process you're trying to diagnose mid-incident, which matters if the leak itself is load-dependent and slowing the process changes its behavior. It's also intrusive in a narrower sense: only one tracer can attach to a process at a time via ptrace, so you can't run strace alongside another debugger.
bpftrace (or a lower-level eBPF tool) attaches via kernel tracepoints/kprobes rather than stopping the process at all, so overhead is far lower (typically negligible for aggregated counting, and still much cheaper even for per-event tracing) and it doesn't monopolize a ptrace slot. For example, bpftrace -e 'tracepoint:syscalls:sys_enter_openat /pid == <pid>/ { printf("%s opened %s\n", comm, str(args->filename)); }' gets you the same "what's being opened" visibility as strace's -e trace=openat, with much less impact on the traced process, but it requires bpftrace/eBPF tooling to be available on the host (not always true, especially on older kernels or heavily locked-down environments) and has a steeper authoring curve for anything beyond straightforward tracepoint-argument printing. In practice: reach for strace first for a quick, ad-hoc look when the process can tolerate the slowdown; reach for bpftrace when the process is latency-sensitive, when you need this running continuously as a low-overhead production diagnostic, or when ptrace's single-tracer restriction is already in the way of something else attached to the process.
You need to rotate logs atomically across multiple processes writing to the same filename. Explain how rename(2) enables atomic rotation, what happens to existing file descriptors after rename, and when copytruncate is required. Propose a robust log rotation strategy that avoids losing logs and works with long-lived processes that keep files open.
Sample Answer
Why rename() enables atomic rotation
rename(oldpath, newpath), when both paths are on the same filesystem, is a single atomic kernel operation: the directory entry newpath is made to point at oldpath's inode, and if newpath already existed, it is atomically replaced (unlinked) as part of that same operation. There is no window where newpath is momentarily missing, and no window where a reader opening newpath could see a partially-written file at that name. This is exactly the property log rotation relies on: rename(current.log, current.log.1) moves the old log out of the way in one step, with no interval where the log path doesn't resolve to something.
What happens to already-open file descriptors after the rename
An fd that was already open on the file before the rename keeps referring to the SAME underlying inode regardless of what any directory entry now says, because rename() only changes which name in the directory tree points at that inode; it does not touch any process's open file descriptors. So a long-lived process that opened current.log before rotation and is still writing through that fd keeps writing to the RENAMED file, now called current.log.1, because the fd was bound to the inode at open time, not to the path string. This is precisely why rename-based rotation requires the writing application to reopen the log file (conventionally on receiving SIGHUP) after rotation; without that reopen, the application's writes silently continue landing in the rotated-away file forever, and the freshly created current.log stays empty from that writer's perspective even though the file on disk with that name is brand new.
When copytruncate is required instead
If the writing process cannot be signaled or otherwise made to reopen its log fd (a third-party binary with no reopen hook, or a process that can't safely be restarted), copytruncate is the fallback: copy the current file's content out to the rotated name, then ftruncate() the ORIGINAL file back to zero length in place, so the still-open fd keeps writing to the same inode and the same name. The caveat: after truncation the fd's write offset is unchanged unless the fd was opened with O_APPEND (in which case O_APPEND makes every write() reposition to the file's current end before writing, regardless of the fd's stored offset, so each write recomputes its position from the file's actual current end), so without O_APPEND the next writes can land at the old offset past the new end-of-file, leaving a gap of null bytes until the application's position catches up on its own. Copytruncate is also not atomic the way rename is: there is a brief window between the copy and the truncate where a concurrent write can land in a region already captured by the copy, or be lost from both copies, so it is a fallback for when rename's atomicity genuinely isn't available, not a strict improvement on it.
A robust rotation strategy
Prefer rename() plus a signal-driven reopen (a SIGHUP handler that calls close() then open(path, O_APPEND | O_CREAT, mode) on the log path) as the primary strategy, since it is atomic and loses no log data; fall back to copytruncate, always paired with O_APPEND on the writer's fd, only when the writer genuinely cannot be made to reopen. Keep enough rotated generations for the retention policy, and compress older generations asynchronously so the rotation step itself stays fast and doesn't block the writer.
A second worked example built on the same atomicity fact: safe config replacement
The same rename() guarantee is used for a related but distinct problem: publishing a new version of a config file (potentially secret-bearing) without ever exposing a partially-written or wrongly-permissioned file at the real path. The pattern: write the new content to a TEMPORARY file in the SAME directory as the target (same filesystem is required here too, since rename() across filesystems is not atomic and in fact fails with EXDEV), fsync() that temp file so its content is durable on disk before it's ever visible under the real name, then fchmod()/fchown() the temp file to the FINAL intended mode and ownership BEFORE the rename, not after. That ordering matters specifically for secrets: if the mode is fixed up after the rename instead of before, the file is briefly visible at its real, well-known name with an overly permissive mode, a real exposure window even if it lasts only milliseconds, and even a very short window is enough for a concurrently running process that happens to be watching that path to read it. Then rename(tmp, target) atomically publishes the new content, and finally fsync() the containing DIRECTORY's own file descriptor as well, a commonly missed step, since the directory entry update itself needs its own fsync to be durable against a crash; without it, a crash immediately after rename could leave the directory entry pointing at the old inode again on some filesystems after recovery, even though the rename() call itself returned success.
How would you use inotify(7) to watch configuration files and directories for changes and trigger a reload in a service? Cover the resource limits (inotify max_user_watches), race conditions (e.g. moved or renamed files), and alternatives such as fanotify or eBPF-based watchers for large-scale monitoring with lower overhead.
Sample Answer
inotify(7) lets a process ask the kernel to notify it, as a readable fd, when specific files or directories change, which is the standard building block for "reload the config when it changes" without polling.
1. Using inotify to watch config and trigger a reload
inotify_init1() creates an inotify fd; inotify_add_watch(fd, path, mask) registers a watch on a path with a bitmask of event types (IN_MODIFY, IN_CREATE, IN_DELETE, IN_MOVED_FROM, IN_MOVED_TO, IN_CLOSE_WRITE, and others). For a config-reload use case, IN_CLOSE_WRITE (fired when a file opened for writing is closed) is usually the more reliable signal than IN_MODIFY: many editors and deployment tools write a config in several small writes, so IN_MODIFY can fire repeatedly mid-write, and a reload triggered on the first one can read a half-written file. The service reads events off the inotify fd (each event is a struct inotify_event, optionally followed by a filename) in an event loop, typically plugged into the same epoll loop as everything else since the inotify fd is just another readable fd, and debounces/coalesces bursts of events (a single "save" in many editors fires several) before actually triggering the reload.
2. Resource limits
/proc/sys/fs/inotify/max_user_watches caps the number of watches a single real user ID can hold across all its processes; it's per-user, not per-process, so a host running several services that each watch a directory tree can collectively exhaust it even though no individual service looks excessive. inotify is not recursive: watching a directory tree means adding one watch per subdirectory yourself, so watching a large tree can consume watches fast. There's also a per-user max_user_instances limit (how many inotify fds/instances a user can hold) and a max_queued_events limit on the kernel's event queue for a given instance; if events arrive faster than the consumer drains them, the queue can overflow, which surfaces as a single IN_Q_OVERFLOW event (with no per-file detail) and silent loss of the events that overflowed. A consumer that relies purely on the event stream without ever cross-checking has no way to tell it missed something unless it specifically watches for IN_Q_OVERFLOW and reacts by doing a full resync (re-reading the config from disk unconditionally) rather than trusting the stream was complete.
3. Race conditions: moved and renamed files
inotify watches track a specific inode (the filesystem's internal file identity), not a path string. The standard "atomic config swap" pattern many tools use, write a new version to a temp file, then rename() it over the original path, breaks a watch placed directly on the original file: after the rename, the watch you had is now watching the old inode (which the rename replaced at that path), and typically fires IN_MOVE_SELF/IN_ATTRIB once and then the watch becomes invalid, it does not automatically start watching whatever new inode now occupies that path. The correct pattern is to watch the containing directory, not the file itself, for IN_MOVED_TO/IN_CREATE/IN_CLOSE_WRITE on the filename you care about, and re-open (and, if you want live updates on that specific file going forward, re-watch) the target whenever it reappears at that path. There's also a residual time-of-check-to-time-of-use gap between "receive the event" and "actually read the file": the file can be rewritten again in the interval, so a defensive reloader re-checks a checksum or mtime, or is simply willing to reload again on the next event rather than assuming the read it just did is final.
4. Alternatives for large-scale monitoring with lower overhead
fanotify(7) can watch an entire mount rather than needing one watch per path, gets richer events (including, in newer modes, permission events that can allow/deny an access before it completes), and avoids inotify's per-directory watch-count overhead for monitoring broad filesystem activity; it's the mechanism behind most Linux-based AV/DLP-style file-activity monitoring, though historically required CAP_SYS_ADMIN (a Linux capability: a narrow, named slice of root's privilege that can be granted independently of full root access; later kernels added narrower FAN_REPORT_* modes that need less). eBPF-based watchers, hooking VFS-layer tracepoints or LSM (Linux Security Module) hooks such as security_file_open, can observe filesystem activity system-wide with much lower per-watch overhead than inotify's per-path bookkeeping and without the max_user_watches ceiling at all, at the cost of real complexity: kernel-version sensitivity, BPF program verification, and typically CAP_BPF/CAP_SYS_ADMIN (often effectively root) to load the program. For "reload my own service's config directory," inotify on the containing directory is the right, simple tool; fanotify or eBPF-based watching is for a different problem, broad, system-wide or security-monitoring-grade file-activity visibility, not a single service's config-reload path.
What is a zombie (defunct) process on Unix/Linux? Explain how it is created, how to detect zombies on a running host (commands and /proc files), the consequences for system resources (PID table exhaustion), and strategies to ensure children are properly reaped in long-running services or supervisors.
Sample Answer
What a zombie is
A zombie (also called "defunct") is a process that has already called _exit() (or been killed) and released essentially everything it owned, memory, file descriptors, and any other resources, but whose EXIT STATUS entry is still sitting in the kernel's process table because the parent hasn't yet called wait()/waitpid() to collect it. It isn't "still running" in any meaningful sense, no CPU time, no memory footprint worth mentioning, it's a lightweight bookkeeping record (essentially a PID plus an exit status) that POSIX requires the kernel to keep around until a parent explicitly retrieves it, because a parent is always entitled to learn how its child exited.
How it's created
Process A fork()s child B; B exits (normally, via exit()/_exit(), or terminated by a signal); the kernel converts B into a zombie and delivers SIGCHLD to A. If A never calls wait()/waitpid(), no signal handler installed, ignoring SIGCHLD without the SA_NOCLDWAIT auto-reap behavior, or simply stuck/busy and never getting around to it, B remains a zombie indefinitely, until A itself exits, at which point B is reparented (to init/PID 1 historically, or to whatever process has registered itself as a "subreaper" via prctl(PR_SET_CHILD_SUBREAPER) on modern Linux), and that new parent reaps it.
Detection
ps aux (or more precisely, ps -eo pid,ppid,stat,cmd) shows Z in the STAT column with the command name suffixed <defunct>. MEASURED, a zombie I deliberately created and captured: ps -o pid,ppid,stat,cmd -p 5195 showed 5195 5193 Z [zombie_demo] <defunct>. The raw kernel-level view is /proc/<pid>/stat, whose third whitespace-separated field is a single character giving process state; cat /proc/5195/stat | awk '{print $3}' confirmed the literal character Z. It's worth explicitly distinguishing a zombie (Z) from a similar-looking but unrelated state, D (uninterruptible sleep): D means a process is blocked inside a kernel operation, usually disk or storage I/O, or a driver wait, that cannot even be interrupted by a signal, it is still fully alive, still consuming resources, whereas Z is a dead process consuming almost nothing but a table slot. A fast host-wide sweep is ps -eo stat= | grep -c Z; pstree -p is the useful next step, since it shows WHICH parent owns a cluster of zombies, which is the process you actually need to fix.
Consequences
Each zombie's process-table entry occupies one PID out of a finite, GLOBAL PID space (/proc/sys/kernel/pid_max, classically 32768 on older/legacy Linux configurations, tunable much higher, up to roughly 4 million on 64-bit systems, and many modern distros ship a higher default out of the box; treat 32768 as the traditional textbook figure, not a universal constant, since it varies by distro and kernel configuration). Practically: a long-running process that forks repeatedly without reaping any children will, given enough time, exhaust available PIDs for the ENTIRE HOST, not just for itself, since PID space is shared system-wide, at which point fork() anywhere on the box starts failing with EAGAIN, an outage that looks completely unrelated to its actual root cause unless whoever's investigating knows to check ps/pstree for a zombie pileup first.
Reaping strategies for long-running services/supervisors
- A blocking
wait()/waitpid(pid, &status, 0)right after eachfork(), fine when the supervisor only ever has one child in flight at a time, wrong the moment it needs to do anything else concurrently. - A
SIGCHLDhandler that loops onwaitpid(-1, &status, WNOHANG)until it returns 0 (nothing left to reap right now) or-1/ECHILD(no children at all). The loop matters because SIGCHLD, like other standard (non-realtime) signals, is not queued and can coalesce: several children exiting in quick succession can result in a single handler invocation, so a handler that reaps only one child per call will systematically leak zombies under load, exactly when the supervisor is busiest. - Explicit
signal(SIGCHLD, SIG_IGN)(orsigactionwithSA_NOCLDWAIT) when the exit status genuinely doesn't matter, this tells the kernel to auto-reap children the instant they exit, so they never become zombies at all. Correct for pure fire-and-forget children; wrong the moment you need the exit code or signal to decide restart/log/quarantine behavior.
The concrete operational motivation for a scanning/sandboxing daemon
A daemon that spawns children specifically for scanning or sandboxing, a security scanner forking a per-file analysis process, say, must ACTIVELY reap them: waitpid(-1, &status, WNOHANG) on every pass through its own event loop, or a SIGCHLD handler doing the same loop, or those scan-worker zombies accumulate silently. The dangerous part is that they accumulate WITHOUT tripping the metrics anyone's actually watching: a zombie costs almost no CPU or memory, so the daemon's own health checks look completely normal while ps/PID-table headroom quietly degrades in the background. During an actual incident, a responder who tails logs and checks top/CPU/RSS sees a "healthy" daemon and, separately, a mysteriously unresponsive host that can no longer fork anything, and the connection between the two isn't obvious unless you specifically know to look for unreaped children. That's exactly the incident-response blind spot this creates: the thing that's actually broken doesn't show up anywhere near the alert that fired.
What does umask() do, how does it interact with file creation permissions, and why is it important when writing tools that create reports, temporary files, or secret-bearing artifacts?
Sample Answer
What umask() does
umask(mask) sets a per-process file mode creation mask. It doesn't create or restrict files directly; instead, it's subtracted from the permission bits an application REQUESTS at file or directory CREATION time, for calls like open(path, O_CREAT, mode) and mkdir(path, mode). The actual permission bits the kernel grants are computed as requested_mode & ~umask, i.e. any bit set in the umask is cleared from the requested mode, never added. Crucially, umask only ever removes permission bits from what was requested; it has no effect on chmod() of an existing file, and it doesn't change the mode value the application itself passes in, only what the kernel ultimately grants at the moment of creation.
A concrete example
With the common default umask 0022, a call to open(path, O_CREAT, 0666) produces a file with mode 0644 (0666 & ~0022 = 0644): group and other lose the write bit, owner keeps read/write. The same umask applied to mkdir(path, 0777) yields a directory with mode 0755.
Why it matters for tools that create reports, temp files, or secret-bearing artifacts
umask is inherited from the parent process, typically the shell or the service manager that launched the tool, and that inherited value is not something the tool's own code controls unless it explicitly overrides it. That makes it an ambient, environment-dependent setting: an interactive shell might run with umask 0022, while a cron job, a systemd service, or a container entrypoint can easily run with a different, sometimes looser umask (0002, or in some misconfigured base images, 0000) depending on how it was configured. A tool that requests a "reasonably conservative-looking" mode like 0644 and trusts the ambient umask to tighten it further is at the mercy of whatever environment happens to invoke it. In an environment with a loose or zero umask, a secret-bearing file the developer believed would end up 0600 can instead end up world-readable, not because the code did anything wrong in isolation, but because it relied on an environmental factor it never verified.
Practical guidance
For anything sensitive, don't rely on the ambient umask at all. Either call umask(0) explicitly at process startup and then pass the EXACT desired mode to every subsequent open()/mkdir() call, removing the dependency on the caller's environment entirely, or fchmod() the file descriptor immediately after creation to the exact intended mode, before any content is ever written to it, so there is no window where a wrong (looser) mode is live on a file that might already contain sensitive data. The fchmod-on-fd approach mirrors the same act-on-the-descriptor-not-the-path discipline that generally defends against TOCTOU races: it fixes the permission on the specific object you already hold open, rather than depending on a race-prone or environment-dependent side effect happening correctly on its own.
Unlock Full Question Bank
Get access to all 11 System Calls & the Kernel Interface interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.