Answer: A system call is the interface between user-space programs and the kernel. Since user processes run in a restricted CPU mode (ring 3 on x86), they cannot directly access hardware or kernel data structures. A syscall is a controlled entry point into the kernel: the process sets up arguments (in registers) and executes a special instruction (syscall on x86-64, svc on ARM) that transitions the CPU to privileged mode (ring 0), where the kernel performs the requested operation and returns the result.
Answer:
User code puts syscall number in rax, arguments in rdi, rsi, rdx, r10, r8, r9.
Executes syscall instruction — CPU saves rip/rflags/rsp to kernel-defined locations, switches to kernel stack, loads kernel entry point from MSR (LSTAR).
Kernel handler (entry_SYSCALL_64) runs, dispatches to syscall table entry.
Result returned in rax (negative = errno).
sysretq returns to user mode, restores registers.
Answer: A table (array of function pointers) in the kernel mapping syscall numbers to handler functions. On Linux x86-64: sys_call_table[] in arch/x86/entry/syscall_64.c. Syscall 0 = read, 1 = write, 2 = open, etc. (per <asm/unistd_64.h>).
syscall() and a libc wrapper?Answer: libc wrappers (e.g., read(), write()) call the actual kernel via syscall. They handle: errno setting (from negative return value), argument type conversions, and sometimes add POSIX compatibility behavior. The raw syscall(SYS_read, ...) bypasses libc and calls the kernel directly.
vDSO (virtual dynamic shared object)?Answer: vDSO maps a small kernel-provided shared library into every process's address space. It allows certain syscalls (gettimeofday, clock_gettime, getcpu) to execute in user space without mode switch by reading kernel-maintained data (e.g., time in shared memory). Eliminates syscall overhead for high-frequency time reads.
VVAR and how does it relate to vDSO?Answer: vvar is a read-only memory region mapped alongside vDSO containing data that the kernel updates (e.g., current time, timezone). The vDSO code reads from vvar to implement clock_gettime without entering the kernel. Visible in /proc/<pid>/maps as [vvar] and [vdso].
errno represent?Answer: errno is a thread-local integer variable (defined in <errno.h>) that holds the error code from the last failed syscall. The kernel returns negative errno values; the libc wrapper negates and stores them in errno, then returns -1. EAGAIN, EINTR, ENOENT, etc. are defined error codes.
xxxxxxxxxxausyscall --dump # list all syscall names and numbersman 2 syscalls # manual page listing allcat /usr/include/asm/unistd_64.h # header fileseccomp and how does it restrict syscalls?Answer: Secure Computing mode (seccomp) is a kernel facility to restrict which syscalls a process may make. Mode 1 (strict): only read, write, _exit, sigreturn allowed — anything else → SIGKILL. Mode 2 (BPF filter): a BPF program filters syscalls by number/arguments. Used in containers (Docker seccomp profiles), browsers (Chrome sandbox), and security-critical applications.
ptrace() and how does it work?Answer: ptrace is a syscall that allows one process (tracer) to inspect and control another (tracee). The tracer can: stop the tracee at each syscall entry/exit, read/write its memory and registers, inject signals, and single-step execution. Basis for strace, gdb, and sandboxes. PTRACE_SEIZE allows non-stopping attach; PTRACE_O_EXITKILL kills the tracee if the tracer dies.
Answer: A syscall costs ~100ns on modern hardware (vs. ~1ns for a function call). Costs include: mode switch (ring3→ring0→ring3), kernel stack setup, register save/restore, TLB/cache effects. Spectre/Meltdown mitigations (KPTI page table isolation) add ~5–10% overhead. Batch I/O (readv/writev, io_uring) amortizes this cost.
io_uring and why is it significant?Answer: io_uring (Linux 5.1+) is an async I/O interface using shared ring buffers (submission queue + completion queue) between user space and kernel. Eliminates syscall overhead per operation by batching I/O through shared memory. Supports pre-registered buffers, fixed files, linked requests. Used in high-performance databases (PostgreSQL, RocksDB) and networking. Can operate entirely without syscalls for hot paths.
read() and pread()?Answer: read(fd, buf, n) reads from the current file position (maintained per open file description) and advances it. pread(fd, buf, n, offset) reads from the specified offset without changing the file position — atomic offset+read. Essential for multi-threaded file access where threads share an FD.
select(), poll(), and epoll()?Answer:
select(): monitors up to FD_SETSIZE (1024) FDs using bit arrays. O(n) scan each call. Low FD limit.
poll(): no FD limit (array of structs), O(n) scan each call. Kernel copies the entire array each time.
epoll(): kernel maintains an interest set. epoll_wait() returns only ready FDs — O(1) for notification. Scales to millions of connections. Edge-triggered (EPOLLET) vs level-triggered modes.
splice() syscall?Answer: splice() moves data between a file descriptor and a pipe (or between two pipes) without copying to user space — zero-copy within the kernel. Used for efficient data forwarding (e.g., web server sending file to network socket: splice(file, NULL, pipe[1], ...) then splice(pipe[0], NULL, socket, ...)).
sendfile()?Answer: sendfile(out_fd, in_fd, offset, count) transfers data from a regular file to a socket directly in the kernel, bypassing user-space copy. One syscall for data transfer. Used by web servers (nginx) for efficient static file serving. Similar to splice() but specifically for file-to-socket.
mmap()'s MAP_SHARED vs MAP_PRIVATE?Answer: MAP_SHARED: writes are visible to other processes mapping the same file/object and are written through to the file. MAP_PRIVATE: copy-on-write — writes create private copies invisible to others and not written to file. MAP_ANONYMOUS | MAP_PRIVATE: anonymous memory (not backed by file) — basis for malloc's large allocations.
munmap() do?Answer: munmap(addr, length) removes a memory mapping. Pages are returned to the OS. Any further access to the region causes SIGSEGV. Does not guarantee writes to MAP_SHARED mappings are flushed to disk — use msync() for that.
msync() and when is it needed?Answer: msync(addr, length, flags) flushes mmap-ed file data back to disk. MS_SYNC — synchronous (waits for completion). MS_ASYNC — asynchronous (schedules flush). MS_INVALIDATE — invalidates other mappings. Required for durability of file-backed shared mappings.
fcntl() used for?Answer: File control operations on open FDs:
F_GETFL/F_SETFL — get/set file status flags (e.g., O_NONBLOCK, O_APPEND).
F_GETFD/F_SETFD — get/set FD flags (e.g., FD_CLOEXEC).
F_DUPFD — duplicate FD.
F_SETLK/F_SETLKW — POSIX advisory file locking.
F_OFD_SETLK — open file description locks (per open-file, not per-process).
Answer: User space: where processes run, restricted CPU mode (ring 3), cannot access hardware directly, isolated virtual address space. Kernel space: privileged CPU mode (ring 0), full hardware access, manages all processes. The boundary is crossed via: system calls, interrupts, exceptions, and signals. The CPU hardware enforces this via protection rings.
Answer: The kernel manages: page tables (virtual-to-physical mapping), physical page allocation (buddy allocator), page replacement (when RAM is full), copy-on-write for fork, demand paging (load pages on fault), memory-mapped files, swap. User space calls mmap/brk and the kernel manages the underlying physical resources.
Answer: Kernel threads (e.g., kworker, ksoftirqd) run entirely in kernel space, have no user address space, and are scheduled by the kernel. User threads (pthreads on Linux) are implemented via clone(CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|...) — they are kernel-scheduled tasks sharing the parent's address space. Linux uses a 1:1 model (one kernel scheduling entity per user thread).
Answer: Kernel preemption (enabled in most kernels via CONFIG_PREEMPT) allows the kernel to preempt a task running in kernel mode (e.g., in a syscall) when a higher-priority task becomes runnable. Without preemption, a task can hold the CPU until it explicitly yields or exits the kernel. Low-latency kernels use PREEMPT_RT for near-hard-real-time behavior.
Answer: A kernel oops is a non-fatal kernel error — the kernel logs the error (register dump, call trace) and continues (usually killing the offending process). A kernel panic is unrecoverable — the kernel halts, printing the panic message and optionally triggering kdump. panic_on_oops=1 in sysctl converts oops to panics.
Answer: Kernel modules are loadable object files (.ko) that extend kernel functionality without rebooting — add device drivers, filesystems, networking protocols. Loaded with insmod/modprobe, unloaded with rmmod. They run in ring 0 with full kernel access. A buggy module can cause oops/panic.
kprobes and how is it used?Answer: kprobes is a kernel instrumentation mechanism that allows setting breakpoints at arbitrary kernel addresses (functions or instructions). When hit, a handler runs. Used by strace alternatives, SystemTap, and bpftrace. No kernel recompilation needed. kretprobes intercept function returns.
Answer: The 64-bit virtual address space is split: user space occupies the lower half (0 to ~128TB, 0x0 to 0x7FFFFFFFFFFFFFFF) and kernel space the upper half (0xFFFF800000000000 onwards). KPTI (Kernel Page Table Isolation, Meltdown mitigation) maps minimal kernel pages in user-space page tables to prevent speculative leakage.
CONFIG_KALLSYMS?Answer: A kernel build option that includes all kernel symbol names in the kernel image, enabling human-readable call traces in oops/panics (instead of raw addresses). Exposed via /proc/kallsyms. Required for many profiling tools (perf, ftrace, kprobes).
Answer: KASLR randomizes the load address of the kernel image at boot to prevent attackers from knowing kernel symbol addresses (needed for exploit techniques like ROP). Combined with ASLR for user space. Can be disabled at boot with nokaslr (needed for some debugging tools that use hardcoded addresses).
Answer: Saving the CPU state (registers, program counter, stack pointer, FPU state) of the currently running process and restoring the state of the next scheduled process. Triggered by: scheduler time slice expiry, blocking syscall, higher-priority wakeup, voluntary sched_yield(). The task_struct stores the context.
task_struct contain?Answer: The kernel's per-process control block. Key fields: PID/TGID, state, priority/niceness, scheduler class, CPU affinity, signal handlers, credentials (uid/gid), file descriptor table, virtual memory (mm_struct), namespace pointers, cgroup membership, accounting statistics, and saved CPU registers (in embedded thread_struct).
Answer: Direct costs: save/restore registers (~100ns), switch page tables (if different process). Indirect costs: TLB flush (most expensive — all virtual-to-physical translations invalidated unless ASID/PCID support), CPU cache cold (next process's data not in L1/L2). PCID (Process Context ID) allows TLB tagging, reducing TLB flush cost on modern Intel CPUs.
Answer: Voluntary (vcsw): process gives up CPU by making a blocking syscall or calling sched_yield(). Involuntary (ivcsw): kernel preempts the process (time slice expired or higher-priority task woke up). High involuntary context switches suggest the process needs more CPU than available. Check with pidstat -w or /proc/<pid>/status (VoluntaryCtxtSwitches, NonvoluntaryCtxtSwitches).
Answer: When a process modifies its page tables (unmap, remap), all CPUs that have cached that process's TLB entries must be notified to flush them (via IPI — Inter-Processor Interrupt). This is a TLB shootdown — expensive on multi-core systems with many CPUs. High rate: perf stat -e tlb:tlb_flush.
Answer: The run queue is the per-CPU data structure holding all runnable tasks (state = TASK_RUNNING). CFS uses a red-black tree ordered by vruntime. The scheduler picks the leftmost node (smallest vruntime = least CPU time received). Real-time queues are separate priority-ordered lists.
schedule() in the kernel?Answer: schedule() is the kernel function that performs a context switch. It: selects the next task (calls pick_next_task() on active scheduling class), calls context_switch() to save/restore state, and returns in the context of the new task. Called from: schedule() explicit calls in blocking paths, and from the tick interrupt when preemption is needed.
Answer: Spinlock: busy-waits (spins) in a tight loop until the lock is available. Cannot sleep while holding. For very short critical sections in interrupt context where sleeping is forbidden. Mutex: blocks (sleeps) the thread if the lock is unavailable, allowing the CPU to run other tasks. For longer critical sections in process context. Spinlocks avoid context switch overhead but waste CPU; mutexes are CPU-efficient for longer waits.
Answer: RCU is a synchronization mechanism optimized for read-heavy, rarely-written shared data. Readers proceed without locks (zero overhead). Writers: make a new version of the data, update the pointer atomically, then wait for all current readers to finish a grace period before freeing the old version. Used extensively in the Linux kernel for routing tables, network configuration, process lists.
softirq and tasklet in the Linux kernel?Answer: softirq (software interrupt): deferred processing units that run in interrupt context after hardware IRQs, but can run in parallel across CPUs. Fixed set (NET_RX, NET_TX, TIMER, etc.). tasklet: built on softirq, runs serialized (same tasklet can't run on two CPUs simultaneously), used for simpler deferred work. Both cannot sleep. For sleepable deferred work: work queues.
Answer: Each process has an mm_struct containing a list of VMAs (Virtual Memory Areas, vm_area_struct), and a page table root (PGD). The CPU MMU uses multi-level page tables (4-level on x86-64: PGD→PUD→PMD→PTE) to translate virtual addresses to physical frames. The kernel manages page allocation, swapping, and COW.
Answer: vm_area_struct describes a contiguous region of a process's virtual address space with uniform properties (permissions, backing store). Each mmap() call, stack growth, or heap expansion creates/extends a VMA. cat /proc/<pid>/maps shows all VMAs. The kernel searches VMAs on page faults to determine if an access is valid.
Answer: Pages are not loaded into physical memory until accessed — memory is allocated lazily. When a process accesses a not-yet-present page, a page fault occurs, and the kernel loads the page from its backing store (file or swap) or allocates a zero page. This makes program startup fast and allows address spaces larger than RAM.
Answer: The kernel's cache of disk file data in RAM. When a file is read, data is placed in the page cache (mapped to specific file+offset). Subsequent reads return cached data. Writes to regular files go to cache first (dirty pages), written back by pdflush/writeback kernel threads or on sync/fsync. cat /proc/meminfo | grep -E "Cached|Buffers".
Answer: File-backed: backed by a file (executable text, mmap'd files, shared libraries). Can be evicted and re-read from disk. Anonymous: no file backing (heap, stack, BSS, MAP_ANONYMOUS). Cannot be re-read from disk — must go to swap if evicted. Anonymous dirty pages are far more expensive to evict.
Answer: Swap provides disk-backed storage for evicted anonymous pages. The kernel swaps out pages when physical RAM is low (via kswapd or direct reclaim). Pages are chosen by LRU lists (active/inactive anon and file lists). Swap-heavy workloads suffer performance degradation (disk I/O vs. RAM access).
kswapd?Answer: kswapd is a kernel thread (one per NUMA node) that asynchronously frees pages when memory gets low (below the pages_high watermark). It scans LRU lists, writes dirty pages, and frees clean ones. If it can't keep up, direct reclaim happens synchronously in the allocation path, causing latency spikes.
vm.swappiness parameter?Answer: Sysctl tunable (0–200, default 60) that controls the kernel's tendency to swap anonymous pages vs. evicting file cache. 0 = prefer evicting page cache, avoid swap. 100 = balance. 200 = aggressively swap anonymous pages. For latency-sensitive workloads: set to 10 or 0. Databases often set it low.
madvise() and its key hints?xxxxxxxxxxmadvise(addr, length, MADV_SEQUENTIAL); // expect sequential accessmadvise(addr, length, MADV_RANDOM); // expect random accessmadvise(addr, length, MADV_WILLNEED); // prefetch pagesmadvise(addr, length, MADV_DONTNEED); // free pages, don't need themmadvise(addr, length, MADV_FREE); // pages can be freed lazilymadvise(addr, length, MADV_HUGEPAGE); // promote to huge pagesposix_fadvise()?xxxxxxxxxxposix_fadvise(fd, offset, len, POSIX_FADV_SEQUENTIAL); // read-ahead hintposix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED); // drop from cacheposix_fadvise(fd, offset, len, POSIX_FADV_RANDOM); // disable read-aheadposix_fadvise(fd, offset, len, POSIX_FADV_WILLNEED); // prefetchAnswer: 2MB (or 1GB) huge pages vs. default 4KB pages. Fewer TLB entries needed for same amount of memory → fewer TLB misses. With huge pages, a 2MB allocation requires 1 TLB entry vs 512. Page fault cost is similar per fault but faults are far less frequent. mmap(MAP_HUGETLB) or Transparent Huge Pages (THP) provide these automatically.
MAP_POPULATE in mmap()?Answer: When MAP_POPULATE is set, mmap() pre-faults all pages in the mapping (populates page tables) before returning. Eliminates subsequent page fault overhead at the cost of upfront latency and memory use. Useful for mappings that will be immediately accessed fully (e.g., reading a file into memory).
MADV_HUGEPAGE vs THP enabled globally?Answer: THP (Transparent Huge Pages) can be set system-wide: always (promote all eligible), madvise (only for regions with MADV_HUGEPAGE), or never. Per-region control via madvise is preferred for databases/latency-sensitive apps as THP promotions cause occasional latency spikes during compaction. Set via /sys/kernel/mm/transparent_hugepage/enabled.
Answer: A PFN identifies a physical memory page (physical_addr / PAGE_SIZE). /proc/<pid>/pagemap maps each virtual page to its PFN (or indicates swap). Useful for: DMA buffer management, NUMA analysis, and understanding physical memory layout.
free() in C?Answer: free() returns the block to malloc's internal freelist — the pages remain in the process's address space (still in RSS). The kernel only reclaims physical pages if malloc calls munmap() (for large blocks) or brk() to shrink the heap. For small blocks, pages stay until the process exits or the OS reclaims them under memory pressure.
Answer:
Pipes — anonymous, unidirectional, kernel FIFO, between related processes.
Named pipes (FIFOs) — filesystem entry, between unrelated processes.
Signals — asynchronous notification.
POSIX message queues — typed messages with priorities.
SysV message queues — older message API.
Shared memory — fastest IPC, requires synchronization (semaphores/mutexes).
POSIX semaphores — process synchronization.
SysV semaphores — older semaphore API.
Unix domain sockets — bidirectional, stream or datagram.
Netlink — kernel↔userspace communication.
D-Bus — message bus for desktop/system services.
Answer: A pipe is a kernel-managed circular buffer (default 64KB on Linux). pipe(fd[2]) creates two FDs: fd[0] (read) and fd[1] (write). Data written to fd[1] is buffered in the kernel until read from fd[0]. Writes block when full; reads block when empty. Atomicity: writes ≤ PIPE_BUF (4096) bytes are atomic.
xxxxxxxxxx// Create/openint fd = shm_open("/myshm", O_CREAT | O_RDWR, 0644);ftruncate(fd, size);void *ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);// Another process:int fd = shm_open("/myshm", O_RDWR, 0);void *ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);// Cleanup:shm_unlink("/myshm");Fastest IPC — processes share physical pages directly; no kernel copy in data path.
Answer: SysV (shmget/shmat/shmdt/shmctl): older API, IPC key-based, persistent until explicitly deleted or reboot, visible in ipcs -m. POSIX (shm_open/mmap): file-descriptor-based, appears in /dev/shm/, more POSIX portable, easier permissions model. Prefer POSIX for new code.
x// Named semaphore (between processes):sem_t *s = sem_open("/mysem", O_CREAT, 0644, 1);sem_wait(s); // acquire (decrement, block if 0)// critical sectionsem_post(s); // release (increment)sem_close(s);sem_unlink("/mysem");
// Unnamed semaphore (threads or forked processes):sem_t sem;sem_init(&sem, 1 /*shared*/, 1 /*initial*/);Answer: A mutex (mutual exclusion lock) is owned by the thread that locked it — only that thread can unlock it. Binary (0/1). Used for protecting critical sections. A semaphore is a counter — any thread can increment it; used for signaling and resource counting. Semaphores don't have ownership; mutexes do. Priority inversion protocols (PI) apply to mutexes.
xxxxxxxxxxmqd_t mq = mq_open("/myqueue", O_CREAT|O_RDWR, 0644, &attr);mq_send(mq, msg, len, priority);mq_receive(mq, buf, buf_len, &priority);mq_unlink("/myqueue");Messages have priorities; higher-priority messages are delivered first. Bounded queue size. Non-blocking via O_NONBLOCK. Notifications via mq_notify().
Answer: Unix domain sockets support: bidirectional communication (pipes are one-way), datagram mode (message boundaries preserved), passing open FDs (SCM_RIGHTS), credentials passing (SCM_CREDENTIALS), and connection to unrelated processes (by path). Use over pipes when you need full duplex, message-oriented protocol, or FD passing.
Answer: Via Unix domain sockets using SCM_RIGHTS ancillary data:
xxxxxxxxxx// Sender:struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);cmsg->cmsg_type = SCM_RIGHTS;*(int *)CMSG_DATA(cmsg) = fd_to_send;sendmsg(socket_fd, &msg, 0);// Receiver:recvmsg(socket_fd, &msg, 0);int received_fd = *(int *)CMSG_DATA(CMSG_FIRSTHDR(&msg));Used by privilege separation daemons, containers, and sandboxes.
Answer: A futex is a kernel primitive for efficient synchronization. When uncontested, lock/unlock happens entirely in user space (atomic operations on a shared integer) — no syscall. Only when contention occurs (futex() syscall with FUTEX_WAIT) does the thread block in the kernel. pthreads mutexes, condition variables, and semaphores are built on futexes.
FUTEX_WAIT and FUTEX_WAKE?Answer: futex(addr, FUTEX_WAIT, expected, timeout) — if *addr == expected, put the calling thread to sleep. futex(addr, FUTEX_WAKE, n) — wake up to n threads waiting on addr. The atomic check-and-sleep prevents lost wakeups. Core building block for all pthreads synchronization primitives.
Answer: A condition variable allows threads to wait for a condition to become true. pthread_cond_wait(cond, mutex): atomically releases the mutex and blocks. When pthread_cond_signal(cond) or pthread_cond_broadcast(cond) is called, waiting threads are woken and reacquire the mutex. Always check the condition in a while loop (spurious wakeups possible).
eventfd() and how is it used for IPC?xxxxxxxxxxint efd = eventfd(0, EFD_SEMAPHORE);// Writer: increment counteruint64_t val = 1;write(efd, &val, sizeof(val));// Reader: decrement counter (blocks at 0)read(efd, &val, sizeof(val));Lightweight in-kernel counter for signaling between processes/threads. Integrates with epoll/select — used in async I/O notification (libuv, Java NIO).
signalfd()?xxxxxxxxxxsigset_t mask;sigemptyset(&mask);sigaddset(&mask, SIGTERM);sigprocmask(SIG_BLOCK, &mask, NULL);int sfd = signalfd(-1, &mask, 0);// Now read signals as file events:read(sfd, &fdsi, sizeof(fdsi));Delivers signals as file descriptor reads — allows signals to be handled via epoll in event loops, avoiding signal handler complexity.
timerfd_create()?xxxxxxxxxxint tfd = timerfd_create(CLOCK_MONOTONIC, 0);struct itimerspec ts = { .it_interval = {1, 0}, .it_value = {1, 0} };timerfd_settime(tfd, 0, &ts, NULL);// Read fires every 1 second:uint64_t expirations;read(tfd, &expirations, sizeof(expirations));Creates a timer that delivers expirations as file descriptor reads. Integrates with epoll for event-driven timer handling.
Answer: vruntime += actual_run_time * (NICE_0_WEIGHT / task_weight). Higher-priority (lower nice) tasks have larger task_weight, so they accumulate vruntime more slowly — they appear to have less runtime proportionally and are picked more often. The task with the smallest vruntime in the red-black tree is always picked next.
Answer: The scheduler tick (via CONFIG_HZ, typically 250Hz or 1000Hz) runs scheduler_tick() which updates vruntime, checks if preemption is needed, and updates load statistics. CONFIG_HZ=250 means 4ms tick. CONFIG_NO_HZ (tickless mode) disables idle ticks, improving power efficiency and reducing latency jitter.
sched_setaffinity() and why use it?xxxxxxxxxxcpu_set_t set;CPU_ZERO(&set);CPU_SET(0, &set); // pin to CPU 0sched_setaffinity(pid, sizeof(set), &set);Pinning a process to specific CPUs improves cache locality (hot L1/L2 cache), reduces TLB shootdowns, and enables NUMA optimization. Used for real-time tasks and high-performance services.
Answer: SCHED_DEADLINE implements the Earliest Deadline First (EDF) algorithm. Tasks specify: runtime (compute time per period), deadline (relative), and period. The scheduler guarantees each task receives at least runtime nanoseconds before its deadline. Uses CBS (Constant Bandwidth Server) to prevent overrun. Most stringent RT guarantee in Linux.
sched_yield() and when should you use it?Answer: sched_yield() voluntarily gives up the CPU, allowing other runnable tasks to run. The calling task is moved to the end of its priority queue. Rarely needed — usually indicates a design problem (busy-waiting). Better alternatives: proper blocking primitives (futex, condition variable, epoll).
Answer: The older O(1) scheduler (pre-2.6.23) maintained run queues indexed by priority, giving O(1) pick-next but had interactive performance issues (heuristics for distinguishing interactive vs. batch tasks). CFS uses the red-black tree with vruntime — O(log N) pick-next but perfectly fair and no heuristics needed. CFS handles interactive performance naturally via vruntime lag.
Answer: CFS periodically (and on CPU idle) balances the run queues across CPUs to ensure fairness. load_balance() migrates tasks from overloaded to underloaded CPUs. Considers: CPU affinity, cache topology (SMT siblings, LLC domains, NUMA nodes). Migration cost increases with NUMA distance.
NUMA balancing in Linux?Answer: Automatic NUMA Balancing (controlled by kernel.numa_balancing sysctl) periodically unmaps process pages and re-faults them to detect which NUMA node accesses them. It then migrates pages to the node where the accessing thread runs, improving memory locality. Can cause latency spikes from the fault-and-migrate process.
Answer: The scheduler organizes CPUs into a hierarchy of scheduling domains reflecting hardware topology: SMT siblings (cores sharing an L1 cache) → CPU cores → NUMA nodes. Load balancing within a domain considers the topology's migration cost. This lets the scheduler prefer keeping tasks close to their data.
isolcpus and how is it used?Answer: isolcpus=2,3 kernel boot parameter isolates CPUs 2 and 3 from the scheduler — no tasks are automatically scheduled there. To run on isolated CPUs: taskset -c 2 ./prog. Used for real-time tasks, DPDK, or latency-sensitive applications that need exclusive CPU access.
Answer: A hardware interrupt is an asynchronous signal from a hardware device (network card, disk controller, timer) to the CPU, requesting attention. The CPU saves its current state and executes the registered interrupt handler (ISR). Linux splits IRQ handling into: top half (ISR — fast, runs with interrupts disabled) and bottom half (softirq/tasklet — deferred, runs with interrupts enabled).
Answer: An ISR runs in interrupt context: no process context, cannot sleep, cannot call blocking functions, must be fast (< few microseconds). It should acknowledge the hardware and schedule deferred work (bottom half) for slower processing. Accesses shared data with spinlocks (not mutexes).
Answer: NAPI (New API) for network cards: instead of an interrupt per packet (high-rate bombardment), receive one interrupt, then poll the NIC in a softirq to drain the receive queue. After draining, re-enable interrupts. Reduces interrupt overhead at high traffic rates. ethtool -C eth0 rx-usecs 50 configures coalescing in the NIC hardware.
xxxxxxxxxxcat /proc/irq/<irq_num>/smp_affinity # CPU bitmask (hex)echo 04 > /proc/irq/<irq_num>/smp_affinity # bind to CPU 2# Or with irqbalance daemon (automatic distribution)systemctl start irqbalancePinning IRQs to specific CPUs reduces cache bouncing and enables RSS/RPS network scaling.
Answer: Hardware IRQ is triggered by physical devices, running in hardware interrupt context. Softirq is a deferred mechanism that runs after hardware IRQs, in interrupt context but with interrupts re-enabled. There are 10 fixed softirq types (HI, TIMER, NET_TX, NET_RX, BLOCK, etc.). Each CPU has its own ksoftirqd thread for soft IRQ overload.
ksoftirqd?Answer: A per-CPU kernel thread that handles softirq processing when softirqs are generated faster than they can be processed inline (after hard IRQ handlers or local_bh_enable()). If too many softirqs are pending, ksoftirqd runs to prevent monopolizing interrupt context. High ksoftirqd CPU use = high softirq load (often network receive).
kill() and raise() system calls?Answer: kill(pid, sig) sends a signal to another process (or process group if pid=0, or all processes if pid=-1). raise(sig) sends a signal to the calling process (equivalent to kill(getpid(), sig)). Also: tkill(tid, sig) sends to a specific thread; tgkill(tgid, tid, sig) does so with safety check.
sigaction() vs signal()?Answer: signal() is simple but has implementation-defined behavior (SA_RESTART, signal mask during handler). sigaction() provides full control: SA_RESTART (auto-restart interrupted syscalls), SA_SIGINFO (receive siginfo_t with sender PID, etc.), SA_NODEFER (don't block signal in handler), custom signal mask during handler. Always use sigaction() for robust signal handling.
Answer: Only async-signal-safe functions can be called from signal handlers. These are functions that are reentrant or don't use non-reentrant resources. Safe: write(), _exit(), sigprocmask(), simple arithmetic. Unsafe: printf(), malloc(), free(), mutex_lock(). Using unsafe functions in handlers causes undefined behavior (deadlock, corruption).
xxxxxxxxxxcat /proc/sys/kernel/rtsig-max # max queued RT signals (older kernels)ulimit -i # SIGQUEUE limit (modern)# Per-process:cat /proc/<pid>/status | grep SigQRT signals queue (multiple signals of same number are NOT merged). Queue depth bounded by RLIMIT_SIGPENDING. If full, sigqueue() returns EAGAIN.
| Namespace | Flag | Isolates |
|---|---|---|
| Mount (mnt) | CLONE_NEWNS | Filesystem mount tree |
| UTS | CLONE_NEWUTS | Hostname, NIS domain |
| IPC | CLONE_NEWIPC | SysV IPC, POSIX MQs |
| PID | CLONE_NEWPID | Process IDs |
| Network | CLONE_NEWNET | Network interfaces, routing, firewall |
| User | CLONE_NEWUSER | UIDs/GIDs (UID 0 in namespace = unprivileged outside) |
| Cgroup | CLONE_NEWCGROUP | cgroup root view |
| Time | CLONE_NEWTIME | Clock offsets |
xxxxxxxxxx// Create new namespaces at fork:clone(child_func, stack, CLONE_NEWPID | CLONE_NEWNET | SIGCHLD, NULL);// From a running process:unshare(CLONE_NEWNS | CLONE_NEWPID);// Join existing namespace:int nsfd = open("/proc/<pid>/ns/net", O_RDONLY);setns(nsfd, CLONE_NEWNET);Or from shell: unshare --pid --mount --net bash.
Answer: A PID namespace gives processes an independent PID numbering. Inside the namespace, processes see PIDs starting from 1. PID 1 in the namespace is the namespace's init — if it dies, all processes in the namespace receive SIGKILL. Nested PID namespaces: processes have different PIDs in each ancestor namespace. docker run creates a new PID namespace.
Answer: A network namespace gives processes their own network stack: independent interfaces, routing tables, iptables rules, sockets, and ports. Used by containers for network isolation. ip netns add myns, ip link set eth0 netns myns. Containers connect namespaces via veth (virtual ethernet) pairs.
Answer: cgroups organize processes into hierarchical groups with resource limits and accounting:
cpu: CPU time allocation (cpu.shares / cpu.quota)
memory: memory limit, OOM kill within group
blkio/io: I/O bandwidth and IOPS limits
cpuset: CPU and memory node affinity
pids: number of processes
net_cls/net_prio: network priority
devices: device access whitelist/blacklist
Answer: v1: each subsystem has its own hierarchy; a process can be in different groups for different subsystems — complex and inconsistent. v2 (unified hierarchy): single hierarchy tree, all controllers applied together, better delegation to non-root. systemd uses v2 on modern distros. /sys/fs/cgroup/ shows v2; previously separate directories.
Answer: Docker creates a container by:
Namespaces: clone() with CLONE_NEWPID | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWUSER flags.
cgroups: creates cgroup entries under /sys/fs/cgroup/ for CPU/memory/blkio limits.
Filesystem: overlayfs for layered filesystem; pivot_root() to switch root.
Capabilities: drops most Linux capabilities (CAP_NET_RAW, etc.).
seccomp: applies syscall filter profile.
Answer: Capabilities split the all-or-nothing root privilege into granular permissions: CAP_NET_BIND_SERVICE (bind ports < 1024), CAP_SYS_PTRACE (ptrace), CAP_NET_ADMIN (network config), CAP_SYS_ADMIN (many admin ops), CAP_KILL (send signals to any process), etc. Allows services to run as non-root with only needed privileges.
xxxxxxxxxxcapsh --print # current capabilitiesgetcap /usr/bin/ping # file capabilitiessetcap cap_net_raw+ep /usr/bin/pingunshare and nsenter?xxxxxxxxxxunshare --pid --fork --mount-proc bash # new PID/mount namespacensenter -t <pid> --net bash # enter network namespace of PIDnsenter --all -t <container_pid> # enter all namespacesunshare creates new namespaces for the calling process. nsenter joins existing namespaces.
Answer: OverlayFS merges multiple directory layers into a single view. A container has: immutable lower layers (image layers) and a upper (writable container layer). Reads check upper first, then lower. Writes go to upper (copy-on-write). Deletes create whiteout files. Efficient: image layers are shared across containers.
fork() and vfork()?Answer: fork() creates a full copy-on-write address space clone. vfork() creates a child that shares the parent's address space — parent is suspended until the child calls exec() or _exit(). vfork() is faster (no page table clone) but dangerous (child must not return from the function that called vfork or modify any data). Largely obsolete — posix_spawn() is preferred.
clone() and how does it differ from fork()?Answer: clone() is the underlying Linux syscall for both fork() and pthread_create(). It takes flags controlling which resources are shared: CLONE_VM (share address space → thread), CLONE_FILES (share FD table), CLONE_SIGHAND (share signal handlers). fork() = clone(SIGCHLD). pthread_create() = clone(CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|...).
execve() and what happens during it?Answer: execve(path, argv, envp) replaces the current process image. Kernel actions: open the ELF binary, verify headers, map text/data/BSS segments, set up stack with argv/envp/auxv, map vDSO and ld.so (dynamic linker), jump to dynamic linker entry point (which resolves shared libraries), then jump to _start in the program. PID, open FDs (without FD_CLOEXEC), signal handlers reset to default.
Answer: ELF (Executable and Linkable Format) is the standard binary format. Components:
ELF header: magic bytes, architecture, entry point, program/section header offsets.
Program headers: segments (LOAD, DYNAMIC, INTERP, NOTE) — used by the OS/dynamic linker at runtime.
Section headers: sections (.text, .data, .bss, .rodata, .symtab, .debug_*) — used by linkers/debuggers.
Dynamic section: shared library dependencies, PLT/GOT addresses.
Symbol table: function/variable names and addresses.
Answer: Lazy dynamic linking mechanism. First call to printf: jumps to PLT stub → GOT entry (initially points back to PLT resolver) → dynamic linker resolves printf's address, stores in GOT. Subsequent calls: PLT stub → GOT (now holds real address) → printf directly. RELRO (-Wl,-z,relro,-z,now) makes GOT read-only after startup for security.
Answer: Address Space Layout Randomization randomizes the base addresses of the stack, heap, and memory-mapped regions (libraries) at program start. Prevents attackers from hardcoding addresses for exploits. Controlled by /proc/sys/kernel/randomize_va_space: 0=off, 1=stack/libs/mmap, 2=also heap. Compile-time PIE (-fPIE -pie) required for executable ASLR.
Answer: The stack pointer (RSP/SP) points to the current top of the stack. A stack frame (or activation record) is the region of the stack allocated for a function call — contains: local variables, saved registers, return address, function arguments (some in registers on x86-64). The frame pointer (RBP/BP) tracks the base of the current frame (may be omitted with -fomit-frame-pointer).
Answer: ROP is an exploit technique that chains existing code snippets ("gadgets" ending in ret) in memory to execute arbitrary logic without injecting new code, bypassing NX (no-execute) protections. Mitigations: ASLR (randomizes gadget addresses), stack canaries (detect overflows), shadow stack (CET), CFI (control flow integrity).
Answer: A random value placed on the stack between local variables and the return address at function entry, checked at function exit. If a buffer overflow overwrites the canary, the check fails and the program is terminated (SIGABRT). Enabled with -fstack-protector or -fstack-protector-all. Does not protect against precise overwrites or non-stack vulnerabilities.
Answer: The SLUB allocator (default since 2.6.22) manages kernel memory for fixed-size objects (inodes, dentries, sk_buff, etc.) using per-CPU caches to minimize locking. Objects of the same size share slabs (groups of pages). Reduces fragmentation and allocation overhead. Exposed via /proc/slabinfo and slabtop.
kmalloc() vs vmalloc() in the kernel?Answer: kmalloc(size, GFP_KERNEL) allocates physically and virtually contiguous memory from the slab allocator — fast, suitable for DMA. vmalloc(size) allocates virtually contiguous but physically non-contiguous pages — used for large allocations where physical contiguity is not required. vmalloc has overhead: extra page table entries, TLB pressure.
Answer: GFP_KERNEL — can sleep, normal allocation. GFP_ATOMIC — cannot sleep (used in interrupt context). GFP_DMA — allocate in DMA-accessible zone. GFP_HIGHUSER — user-space page allocation. GFP_NOWAIT — return NULL if can't immediately satisfy. Using wrong GFP flags (e.g., GFP_KERNEL in interrupt context) is a kernel bug.
Answer: CPUs and compilers reorder memory operations for performance. Memory barriers (smp_mb(), smp_rmb(), smp_wmb(), C11 atomics) prevent reordering across the barrier. Needed when: sharing data between CPUs without locks, implementing lock-free data structures, communicating with hardware (DMA). Without barriers, the other CPU may see stores in a different order.
__builtin_expect and branch prediction?Answer: Modern CPUs predict branch outcomes; misprediction costs ~15 cycles. __builtin_expect(cond, expected) hints to the compiler about likely vs. unlikely paths, enabling better code layout:
xxxxxxxxxxif (__builtin_expect(ptr == NULL, 0)) { /* unlikely error path */ }// Or:Answer: Cache lines are the unit of cache memory (typically 64 bytes on x86). Any access to any byte loads the entire 64-byte line. False sharing: two threads modifying different variables in the same cache line causes cache line ping-pong between CPUs → severe performance degradation. Fix: align shared variables to cache line boundaries (__attribute__((aligned(64))), __cacheline_aligned).
__attribute__((packed)) and what are its implications?Answer: Forces the compiler to pack a struct with no padding between members — reduces size but may cause misaligned access on strict-alignment architectures (ARM, SPARC), leading to performance penalties or SIGBUS. Useful for network protocol headers or hardware register maps.
Answer: DMA allows devices (NIC, disk controller) to transfer data directly to/from main memory without CPU involvement. The driver: allocates a DMA buffer (physically contiguous, sometimes with IOMMU mapping), gives the device the physical address, and the device writes directly to RAM. On completion, the device raises an interrupt. Requires cache coherency handling (dma_map_* functions in the kernel manage this).
Answer: IOMMU (I/O Memory Management Unit) provides virtual-to-physical address translation for DMA-capable devices, similar to how the CPU's MMU works for processes. Benefits: prevents DMA from accessing unauthorized memory (security/isolation), allows non-contiguous physical memory for DMA, enables virtualization (devices see guest physical addresses). Intel VT-d, AMD-Vi.
mlock() and why use it?xxxxxxxxxxmlock(addr, length); // lock pages in RAM, prevent swappingmlock2(addr, length, MLOCK_ONFAULT); // lock on first accessmlockall(MCL_CURRENT | MCL_FUTURE); // lock all process memoryUsed by: real-time applications (prevent latency from page faults), security-sensitive code (prevent keys from reaching swap/disk), databases. Requires CAP_IPC_LOCK or setting RLIMIT_MEMLOCK.
perf_event_open() used for?Answer: The syscall for the perf subsystem. Allows user space to access hardware performance counters (cycles, instructions, cache misses, branch misses), software events (context switches, faults), tracepoints, and kprobes. Used by perf, bpftrace (for hardware events), and custom profiling tools. Returns a file descriptor for reading counts or setting up overflow notifications.
Answer: open(file, O_DIRECT) bypasses the kernel page cache — I/O goes directly between user buffer and disk. Requires: aligned buffer (posix_memalign), aligned offset, aligned size (multiple of block size). Used by databases (PostgreSQL, MySQL) that manage their own cache and don't want kernel cache double-buffering.
O_SYNC and O_DSYNC?Answer: O_SYNC: each write() blocks until data and metadata are written to the physical device (equivalent to fsync() after each write). O_DSYNC: blocks until data is written but not necessarily metadata (equivalent to fdatasync()). Provides durability at the cost of latency. Used for journals and WALs.
Answer: Level-triggered (LT, default): epoll_wait returns the FD as ready as long as data is available — safe, easy, but may return the same FD multiple times. Edge-triggered (ET): returns once per new data arrival — must drain completely each time; miss it and you won't be notified again. ET requires non-blocking FDs and careful implementation but is more efficient for high-performance servers.
SO_KEEPALIVE and how does TCP keepalive work?Answer: SO_KEEPALIVE enables TCP keepalive probes — after idle for tcp_keepalive_time seconds (default 2h), the kernel sends probe packets at tcp_keepalive_intvl intervals (default 75s), up to tcp_keepalive_probes times (default 9). If no response, the connection is closed. Used to detect dead peers and prevent firewall/NAT from expiring idle connections.
TCP_NODELAY and when to use it?Answer: By default, TCP uses Nagle's algorithm — buffers small writes and combines them into larger segments to reduce packet count. TCP_NODELAY disables Nagle's algorithm — each write is sent immediately. Needed for low-latency request-response protocols (interactive SSH, game servers, financial trading). Default: enabled (Nagle on), which improves throughput for bulk transfers.
SO_REUSEPORT and why is it useful?Answer: Multiple sockets can bind to the same IP:port. The kernel load-balances incoming connections/packets across them using consistent hashing. Enables: multiple processes/threads to accept without a common accept loop, eliminates the "thundering herd" on accept(), better multi-core utilization. Used by Nginx worker processes, HAProxy.
SOCK_STREAM and SOCK_SEQPACKET?Answer: SOCK_STREAM (TCP, Unix): reliable, ordered, byte-stream — no message boundaries. Reads may return partial messages. SOCK_SEQPACKET (Unix domain, SCTP): reliable, ordered, with message boundaries preserved — each write is a discrete message, read returns exactly one message. Avoids manual framing protocol for Unix domain IPC.
Answer: SCTP provides: reliable, ordered delivery like TCP, but with message framing (no need for length-prefixing), multi-homing (multiple network paths), multi-streaming (independent streams within one connection, avoiding head-of-line blocking), and four-way handshake. Used in telecom signaling (SS7/Diameter), some clustering protocols.
recv() vs read() on a socket?Answer: Both work on sockets but recv(fd, buf, len, flags) has additional flags: MSG_PEEK (read without consuming), MSG_WAITALL (block until buffer full), MSG_DONTWAIT (non-blocking), MSG_TRUNC (return actual size even if truncated). read(fd, buf, len) is equivalent to recv(fd, buf, len, 0).
TCP_CORK and how does it work?Answer: TCP_CORK (Linux) accumulates data in the send buffer until either the MSS is reached or TCP_CORK is cleared. Used to build complete response headers+body before sending, avoiding Nagle algorithm limitations for chunked writes. Example: write HTTP headers, cork, write body, uncork → single segment.
SO_LINGER and what is it used for?Answer: By default, close() on a socket returns immediately (kernel handles remaining data). SO_LINGER with l_onoff=1, l_linger=N makes close() block up to N seconds waiting for data to be sent and acknowledged, or resets the connection if N=0. Used when you need to ensure data delivery before the socket is fully closed.
inotify and how does it work?xxxxxxxxxxint ifd = inotify_init1(IN_NONBLOCK);int wd = inotify_add_watch(ifd, "/path", IN_CREATE | IN_MODIFY | IN_DELETE);// Read events:struct inotify_event *event;read(ifd, buf, sizeof(buf)); // blocks until events// event->mask contains IN_CREATE, event->name contains filenameinotify lets processes watch filesystem events efficiently without polling. Up to fs.inotify.max_user_watches watches per user.
fanotify?Answer: fanotify is a more powerful filesystem notification API (requires CAP_SYS_ADMIN). Unlike inotify: can watch entire mounts, receive pre-event access decisions (approve/deny file opens — used by antivirus scanners, access control). Used by security tools (ClamAV, auditd, container security).
landlock (Linux 5.13+)?Answer: Landlock is a security module that allows unprivileged processes to restrict their own access to the filesystem. Unlike seccomp (syscall level), landlock operates at the VFS layer. Useful for sandboxing: a process can restrict itself to only specific directories/file types, even without root. Used in browsers and sandboxed applications.
cgroups freezer and cgroups devices controllers?Answer: Freezer: suspends and resumes all tasks in a cgroup simultaneously (SIGSTOP/SIGCONT equivalent for groups). Used by container checkpoint/restore (CRIU). Devices: controls which device files (by major:minor, type c/b) tasks in a cgroup can open. Used to restrict containers to only allowed devices.
CRIU (Checkpoint/Restore In Userspace)?Answer: CRIU dumps and restores the complete state of running processes (memory, FDs, network connections, process tree). The checkpoint creates a set of image files; restore re-creates the exact process state on any compatible system. Used for: container migration, live migration, fast startup (restore vs. cold start).
memfd_create() and what is it used for?xxxxxxxxxxint fd = memfd_create("name", MFD_CLOEXEC | MFD_ALLOW_SEALING);ftruncate(fd, size);void *ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);Creates an anonymous file backed by memory. Unlike shm_open: no filesystem visibility by default, supports sealing (make read-only/immovable after writing). Used for secure IPC (pass fd via SCM_RIGHTS), JIT code buffers, and container image loading.
pidfd_open() (Linux 5.3+)?xxxxxxxxxxint pidfd = pidfd_open(pid, 0);// Send signal:pidfd_send_signal(pidfd, SIGTERM, NULL, 0);// Wait for exit:waitid(P_PIDFD, pidfd, &info, WEXITED);A file descriptor representing a process — race-free PID handling (PID reuse races are eliminated). Can be passed between processes. Integrates with epoll to watch for process exit.
eBPF from a kernel perspective?Answer: eBPF is a safe in-kernel virtual machine: user submits a BPF bytecode program → kernel verifier checks for safety (no loops, no invalid accesses, bounded execution) → JIT-compiled to native code → attached to kernel hooks (kprobes, tracepoints, XDP, etc.). Programs communicate via BPF maps (hash, array, ring buffer). No kernel module required, no stability risk (verifier enforces safety).
Answer: XDP allows eBPF programs to run at the network driver receive path — before the kernel network stack processes the packet. Enables: ultra-high-performance packet processing (line-rate), DDoS mitigation, load balancing (Facebook Katran), software firewalls. Actions: XDP_PASS (normal stack), XDP_DROP (drop), XDP_TX (bounce back), XDP_REDIRECT (redirect to another NIC/CPU queue).
Answer: sk_buff (socket buffer) is the kernel's central network packet structure. Contains: packet data (via DMA to NIC), protocol headers, metadata (timestamps, checksums, routing info). Passed between network stack layers by adjusting head/tail pointers (no data copy). Memory layout allows prepending/appending headers efficiently.
netfilter hooks?Answer: Netfilter hooks are points in the kernel's network stack where packet processing modules can register. Hooks: PREROUTING → INPUT → FORWARD → OUTPUT → POSTROUTING. iptables/nftables use these hooks. Each hook can: accept, drop, modify, or queue packets to user space (NFQUEUE).
Answer: Each process has its own virtual address space (isolated by page tables). The kernel address space is shared across all processes (same physical mapping for all page tables). When a syscall executes, the same kernel code/data is mapped in the current process's page tables (or in a separate PGD with KPTI). Kernel sees all physical memory; a process sees only its own virtual pages.
prctl() used for?xxxxxxxxxxprctl(PR_SET_NAME, "mythread"); // set thread nameprctl(PR_SET_DUMPABLE, 0); // disable core dumps (security)prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); // disable setuid/capabilitiesprctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog); // apply seccomp filterprctl(PR_GET_CHILD_SUBREAPER, ...); // set process as subreapervsyscall region?Answer: vsyscall (older mechanism, pre-vDSO) mapped a fixed virtual address (0xFFFFFFFFFF600000) with commonly used syscall implementations. Fixed address was a security issue (bypasses ASLR). Modern Linux uses vDSO (randomized mapping) instead. vsyscall=emulate kernel parameter makes vsyscall page fault through the kernel for security.
copy_to_user() / copy_from_user() in the kernel?Answer: Kernel functions that safely copy data between kernel and user address spaces. They check that user pointers are valid (not kernel addresses, within user address range) and handle faults gracefully (instead of crashing the kernel). Using plain dereference on user pointers is a kernel bug — use these functions. Returns bytes not copied on error.
wait4() and waitid()?Answer: wait4(pid, status, options, rusage) waits for a child, optionally filling resource usage. waitid(idtype, id, infop, options) is more flexible: can wait on PID, PGID, or pidfd; uses siginfo_t for richer exit info (exit code, signal, CPU times). WNOWAIT option lets you inspect exit status without reaping. waitid with P_PIDFD is the modern race-free interface.
getrandom() syscall?xxxxxxxxxxunsigned char buf[32];getrandom(buf, sizeof(buf), 0); // blocks until seededgetrandom(buf, sizeof(buf), GRND_NONBLOCK); // returns EAGAIN if not seededgetrandom(buf, sizeof(buf), GRND_RANDOM); // read from blocking poolDirect cryptographic random bytes from the kernel. Preferred over /dev/urandom (avoids open+read+close overhead) and safer (available before filesystem, works in chroot/container).
renameat2() with RENAME_ATOMIC?Answer: Standard rename() atomically replaces the destination. renameat2() with RENAME_EXCHANGE atomically swaps two files (both paths remain valid with exchanged content). RENAME_NOREPLACE fails if destination exists (instead of overwriting). Used for atomic configuration updates (swap new config into place without a window where neither exists).
clone3() syscall and what improvements does it bring?Answer: clone3() (Linux 5.3+) is an extensible replacement for clone(). It takes a struct instead of individual arguments, allowing future fields without a new syscall. Added features: set_tid (specify desired PID in namespace), pidfd (return a pidfd for the child), cgroup (place child in a cgroup atomically). Enables race-free process creation with full resource control.