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.
During an outage you must inspect a process's memory layout and open files to identify a leak. Describe which /proc/<pid> entries you would inspect (/proc/<pid>/maps, /proc/<pid>/smaps, /proc/<pid>/fd, /proc/<pid>/status), what useful fields each contains, and concrete commands to extract and interpret the data quickly in real time on a busy host.
Sample Answer
When a process is leaking memory (or you suspect it is) mid-outage, four files under /proc/<pid>/ give you a live, no-restart-needed view of exactly what it has mapped and open, without needing a debugger attached.
1. /proc/<pid>/status
A human-readable summary of the process's memory and identity. The fields worth checking first: VmRSS (current resident set size, physical RAM actually in use right now), VmHWM (high-water-mark RSS, the peak resident size ever reached, useful for confirming whether the process is still growing or plateaued at a historical peak), VmSize (total virtual address space, useful to compare against an RLIMIT_AS if one's set), and Threads (thread count, since a leak that's really "one thread per connection, never cleaned up" shows here just as much as in memory). A quick check: grep -E 'VmRSS|VmHWM|VmSize|Threads' /proc/<pid>/status.
2. /proc/<pid>/maps
A line-per-mapping list of everything in the process's virtual address space: address range, permissions, offset, device, inode, and the backing file (or [heap], [stack], anon for anonymous mappings not backed by a file). This is the fastest way to answer "what does this process actually have mapped, and how many distinct mappings are there," e.g. wc -l /proc/<pid>/maps gives a mapping count, and a leak that manifests as "we keep mmap()'ing and never munmap()'ing" shows up as that count growing unboundedly over time when sampled repeatedly.
3. /proc/<pid>/smaps (or the aggregated smaps_rollup)
The same list as maps, but with per-mapping resident/shared/private/swap breakdowns: Rss, Pss (proportional set size, RSS divided fairly among processes sharing that mapping, the right number to sum across processes without double-counting shared library pages), Private_Dirty (pages modified and not shared, usually the best signal for "memory this process alone is responsible for"), and Swap. For a busy host, /proc/<pid>/smaps_rollup gives the same aggregated totals without walking every individual mapping, which matters because smaps itself can be expensive to read on a process with a very large number of mappings. A quick command: grep -A0 'Private_Dirty' /proc/<pid>/smaps_rollup gives a single-line answer to "how much private, dirty, definitely-this-process's memory is resident."
4. /proc/<pid>/fd
A directory of symlinks, one per open file descriptor, each pointing at what that fd refers to (a regular file's path, socket:[inode], pipe:[inode], etc.). ls -la /proc/<pid>/fd | wc -l gives an open-fd count in one command; comparing that against RLIMIT_NOFILE (the max number of file descriptors this process may have open at once, visible in /proc/<pid>/limits) tells you how close the process is to hitting EMFILE (the error returned once that limit is hit). ls -la /proc/<pid>/fd with the target listing shown (not just the count) quickly reveals what kind of descriptor is accumulating, e.g. a growing list of socket:[...] entries with no matching connection activity points at leaked sockets rather than leaked files.
5. Putting it together on a busy host, quickly
A fast triage sequence: cat /proc/<pid>/status | grep -E 'VmRSS|VmHWM' for the headline number, cat /proc/<pid>/smaps_rollup | grep Private_Dirty to confirm it's genuinely this process's own memory rather than shared pages inflating the RSS figure, wc -l /proc/<pid>/maps sampled twice a minute or two apart to see whether the mapping count itself is growing (mmap leak) versus staying flat while RSS grows (a heap/allocator leak inside existing mappings), and ls /proc/<pid>/fd | wc -l sampled the same way to rule in or out a parallel fd leak. Because all of these are plain files under /proc, none of them require attaching a debugger, sending a signal, or restarting the process, which matters mid-outage when you need the process to keep running while you investigate.
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.
Write C code or pseudocode for a function that copies data from one file descriptor to another robustly. It must correctly handle partial reads, partial writes, EINTR, and end-of-file without corrupting the destination.
Sample Answer
A robust fd-to-fd copy has to get three things right that a naive read()/write() pair does not: a read() can return fewer bytes than requested even before EOF (a "partial read", common on pipes, sockets, and slow devices), a write() can likewise write fewer bytes than you asked for (a "partial write", common once the kernel's internal buffers are under pressure), and either call can be interrupted by a signal and return -1 with errno == EINTR even though nothing actually went wrong, in which case the correct response is simply to retry, not to treat it as a real error.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
/* Copies all bytes from fd_in to fd_out. Returns 0 on success, -1 on error (errno set). */
int copy_fd(int fd_in, int fd_out) {
char buf[8192];
for (;;) {
ssize_t n_read = read(fd_in, buf, sizeof(buf));
if (n_read < 0) {
if (errno == EINTR) continue; /* interrupted before any data was read: retry */
return -1; /* real error, errno already set by read() */
}
if (n_read == 0) break; /* EOF: nothing left to copy */
ssize_t total_written = 0;
while (total_written < n_read) {
ssize_t n_written = write(fd_out, buf + total_written, n_read - total_written);
if (n_written < 0) {
if (errno == EINTR) continue; /* retry the same write, no data lost */
return -1;
}
total_written += n_written; /* advance past a short/partial write */
}
}
return 0;
}
int main(void) {
int fd_in = open("src.txt", O_RDONLY);
if (fd_in < 0) { perror("open src.txt"); return 1; }
int fd_out = open("dst.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd_out < 0) { perror("open dst.txt"); close(fd_in); return 1; }
if (copy_fd(fd_in, fd_out) < 0) {
perror("copy_fd");
close(fd_in);
close(fd_out);
return 1;
}
close(fd_in);
if (close(fd_out) < 0) { perror("close dst.txt"); return 1; }
printf("copy complete\n");
return 0;
}
Run it from an empty directory:
$ printf 'alpha\nbeta\ngamma\n' > src.txt
$ gcc -Wall -Wextra -o copy_fd copy_fd.c
$ ./copy_fd
copy complete
$ diff src.txt dst.txt && echo IDENTICAL
IDENTICAL
(Verified: this exact source compiles cleanly and produces this exact output on Linux, gcc 13.)
Why each piece is necessary, not defensive-programming theater
- The inner
whileloop onwrite()is not optional: a singlewrite()call is only guaranteed to accept as much as it accepts, and silently ignoring the return value (or treating it as all-or-nothing) is the single most common source of silent data corruption in copy routines, because it manifests as "usually works" until the destination is a pipe, a socket, or the source system is under memory pressure. - Retrying on EINTR must retry the SAME write with the SAME remaining data (
buf + total_written,n_read - total_written), not restart the whole buffer, or bytes get duplicated. - EOF is
read()returning exactly 0, not a negative return; conflating "0 bytes read" with an error is a common off-by-one in these loops. - Closing
fd_outand checking its return value matters because a buffered filesystem's actual write errors (out of disk space, quota) can surface onclose()rather than on the precedingwrite()calls, depending on the filesystem and any write-back caching involved; checking only the write() calls and ignoring close()'s return value can mask a failed copy that looks like it succeeded.
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.
Unlock Full Question Bank
Get access to all 45 System Calls & the Kernel Interface interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.