Operating system interview questions: processes, memory, scheduling and deadlock
Operating system interview questions cover how the kernel runs programs: processes and threads, system calls, CPU scheduling, memory management with paging and virtual memory, synchronization primitives, deadlock, and file systems. Campus and fresher rounds ask for definitions and small numeric problems (average waiting time, page faults), while experienced rounds ask you to connect those ideas to real symptoms such as high load, swapping or a process that will not die. Answer with the mechanism, then the trade-off.
By Evin JohnPublished 10 min read
Where OS questions appear
OS theory is a standard part of campus placements and of many software engineering interviews in India and elsewhere, usually alongside DBMS, computer networks and OOP as the "CS fundamentals" round. Systems, embedded, infrastructure and SRE roles go deeper, asking about Linux internals, memory pressure and system calls. Expect a mix of definitions, comparisons ("mutex versus semaphore"), short calculations done on paper, and "what happens when" questions that check you can follow a request from user space into the kernel and back.
Processes, threads and system calls
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is a process, and what does the OS keep about it? | Basics | A program in execution. The kernel tracks it in a process control block: process id, state, saved registers and program counter, memory maps, open files, scheduling priority and accounting. |
| Name the process states and the transitions between them. | Lifecycle | New, ready, running, waiting (blocked) and terminated. Running moves to ready on a timer interrupt, to waiting on I/O, and back to ready when the I/O completes. |
| Process versus thread from the kernel's view? | Isolation | Threads of one process share the address space, heap and file descriptors but each has its own stack and registers. Switching between threads of the same process is cheaper because the memory mappings stay the same. |
| What is a context switch and what does it cost? | Mechanism | Saving one task's registers and loading another's, plus switching page tables if the process changes. The hidden cost is cold caches and a flushed or tagged TLB afterwards. |
| User mode versus kernel mode? | Protection | User code cannot touch hardware or other processes' memory directly. A system call, interrupt or fault switches the CPU into kernel mode, where privileged instructions are allowed. |
| What is a system call? Give examples. | Interface | A controlled entry into the kernel through a trap instruction: open, read, write, fork, execve, mmap, wait. Library calls such as printf eventually make one. |
What do fork and exec do? | Unix model | fork creates a near-copy of the calling process; exec replaces the current program image with a new one. A shell forks, the child execs the command, and the parent waits. |
| What is copy-on-write? | Optimization | After fork, parent and child share physical pages marked read-only. Only when one of them writes is that single page copied, so forking a large process stays cheap. |
| Zombie versus orphan process? | Lifecycle detail | A zombie has exited but its parent has not collected its exit status with wait, so its entry stays in the process table. An orphan's parent died first; it is adopted by init (or a subreaper), which reaps it. |
| What are the main IPC mechanisms? | Communication | Pipes, named pipes, message queues, shared memory with a semaphore, sockets and signals. Shared memory is fastest; message passing is easier to get right. |
| What is an interrupt, and how is it different from a trap? | Hardware interface | An interrupt comes from a device (a timer, a disk finishing a read) at any time. A trap or exception is caused by the running instruction itself, such as a system call or a page fault. |
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
pid_t pid = fork();
if (pid < 0) { perror("fork"); return 1; }
if (pid == 0) { /* child */
execlp("echo", "echo", "hello from the child", (char *)NULL);
perror("execlp"); /* only reached if exec failed */
_exit(127);
}
int status; /* parent */
waitpid(pid, &status, 0); /* reap the child */
if (WIFEXITED(status))
printf("child exited with %d\n", WEXITSTATUS(status));
return 0;
}CPU scheduling
- Preemptive versus non-preemptive scheduling? Preemptive schedulers can take the CPU away from a running task, usually on a timer interrupt. Non-preemptive ones wait until the task blocks or finishes, which is simpler but lets one long task stall everyone.
- Compare FCFS, SJF, SRTF, round robin and priority scheduling. First come first served is simple but suffers the convoy effect. Shortest job first minimizes average waiting time but needs burst lengths you rarely know. Shortest remaining time first is its preemptive form. Round robin gives each task a time slice in turn, good for response time. Priority scheduling can starve low-priority work unless aging raises waiting tasks' priority.
- How do you pick a round robin time quantum? Too small and the CPU spends its time switching; too large and round robin degrades into FCFS. It should be large compared with the context switch cost and cover most short interactive bursts.
- What is a multilevel feedback queue? Several queues with different priorities and quanta. Tasks that use their whole slice move down; tasks that block early (interactive ones) stay high. It approximates SJF without knowing burst lengths.
- Turnaround time, waiting time and response time? Turnaround is completion minus arrival. Waiting is turnaround minus the CPU time actually used. Response time is the delay until the task first runs.
- What does Linux use? For normal tasks, the Completely Fair Scheduler tracked each task's virtual runtime for many years, and from kernel 6.6 the EEVDF scheduler took over that role. Real-time policies (
SCHED_FIFO,SCHED_RR) sit above both. - What is priority inversion? A low-priority task holds a lock a high-priority task needs, while a medium-priority task keeps the low one from running. Priority inheritance, which temporarily boosts the lock holder, is the usual fix.
from collections import deque
def round_robin(bursts, quantum):
remaining = dict(bursts)
queue = deque(name for name, _ in bursts)
clock, finish = 0, {}
while queue:
name = queue.popleft()
run = min(quantum, remaining[name])
clock += run
remaining[name] -= run
if remaining[name] == 0:
finish[name] = clock
else:
queue.append(name)
burst = dict(bursts)
waiting = {n: finish[n] - burst[n] for n in burst} # all arrive at 0
return waiting, sum(waiting.values()) / len(waiting)
waits, avg = round_robin([("P1", 10), ("P2", 4), ("P3", 3)], quantum=2)
print(waits, round(avg, 2)) # {'P1': 7, 'P2': 6, 'P3': 8} 7.0Memory management, paging and virtual memory
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is virtual memory and why have it? | Core idea | Each process sees its own large, private address space. The OS maps it to physical frames, isolates processes, lets memory exceed RAM by keeping some pages on disk, and lets processes share code pages. |
| How does paging translate an address? | Mechanism | The virtual address splits into a page number and an offset. The page table maps the page number to a frame; the offset is added unchanged. Multi-level page tables keep the table small for sparse address spaces. |
| What is the TLB? | Performance | A small cache of recent page translations inside the CPU. A hit skips the page table walk; a miss costs several memory reads. Huge pages make each entry cover more memory. |
| What happens on a page fault? | Mechanism | The CPU traps into the kernel. If the address is valid but the page is not in RAM, the kernel finds a free frame (evicting one if needed), reads the page from disk or zero-fills it, updates the page table and restarts the instruction. If the address is invalid, the process gets a segmentation fault. |
| Paging versus segmentation? | Comparison | Paging uses fixed-size pages and avoids external fragmentation. Segmentation uses variable-size logical segments (code, stack, heap) and suffers external fragmentation. Modern x86-64 systems rely on paging. |
| Internal versus external fragmentation? | Definitions | Internal is wasted space inside an allocated block, such as the unused end of a page. External is free memory split into pieces too small to use, even though the total would be enough. |
| Compare page replacement policies. | Algorithms | FIFO is simple but can evict hot pages. LRU approximates the ideal (Belady's optimal, which needs the future) but is costly to track exactly, so kernels use clock or second-chance approximations. |
| What is Belady's anomaly? | Classic trap | With FIFO, giving a process more frames can cause more page faults for some reference strings. Stack algorithms such as LRU never show it. |
| What is thrashing and how do you stop it? | Symptoms | The working sets of running processes exceed RAM, so the system spends its time paging instead of computing. Reduce the number of active processes, add memory, or use working-set based admission. |
| Stack versus heap memory? | Process layout | The stack holds call frames and is managed automatically per thread; the heap holds dynamically allocated memory managed by the allocator. Stack overflow and heap fragmentation are their typical failures. |
from collections import OrderedDict, deque
def fifo_faults(refs, frames):
memory, order, faults = set(), deque(), 0
for page in refs:
if page not in memory:
faults += 1
if len(memory) == frames:
memory.remove(order.popleft())
memory.add(page)
order.append(page)
return faults
def lru_faults(refs, frames):
memory, faults = OrderedDict(), 0
for page in refs:
if page in memory:
memory.move_to_end(page) # most recently used
else:
faults += 1
if len(memory) == frames:
memory.popitem(last=False) # evict least recently used
memory[page] = True
return faults
refs = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
print("FIFO", fifo_faults(refs, 3), fifo_faults(refs, 4)) # FIFO 9 10
print("LRU ", lru_faults(refs, 3), lru_faults(refs, 4)) # LRU 10 8Synchronization primitives
- What is the critical section problem, and what must a solution guarantee? Mutual exclusion, progress (a free critical section is not left idle by bad scheduling) and bounded waiting (no process waits forever).
- Mutex versus semaphore? A mutex has an owner: only the thread that locked it should unlock it, and it guards one resource. A counting semaphore is a counter with wait (P) and signal (V) that any thread may signal, used to admit up to n users or to signal events. A binary semaphore looks like a mutex but has no ownership.
- What is a spinlock and when is it better than a sleeping lock? It busy-waits instead of sleeping. On a multicore system it wins when the lock is held for less time than a context switch takes, which is why kernels use spinlocks for short sections, often with interrupts disabled.
- How are locks built in hardware? On atomic instructions such as test-and-set, compare-and-swap, or load-linked/store-conditional. Disabling interrupts alone only works on a single core.
- What is a monitor? A language-level construct that pairs a lock with condition variables, so only one thread runs inside at a time and others wait for conditions. Java objects behave like monitors.
- Solve producer-consumer with semaphores. One mutex for the buffer, an
emptysemaphore starting at the buffer size and afullsemaphore starting at 0. Producers wait onemptybefore the mutex, never after, or they can deadlock. - What do the dining philosophers and readers-writers problems teach? Dining philosophers shows circular wait and its fixes (order the forks, or let at most four sit). Readers-writers shows the choice between favoring readers, which can starve writers, and favoring writers.
Deadlock: conditions, prevention, avoidance, detection
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are the four necessary conditions for deadlock? | Theory | Mutual exclusion, hold and wait, no preemption, and circular wait. All four must hold; breaking any one prevents deadlock. |
| How does prevention break each condition? | Strategies | Make resources shareable where possible, request all resources at once, allow resources to be preempted, or impose a global order on resource types so no cycle can form. |
| What is the difference between prevention and avoidance? | Precision | Prevention restricts how requests are made so deadlock cannot occur. Avoidance checks each request at run time and only grants it if the system stays in a safe state. |
| Explain the banker's algorithm. | Avoidance | Each process declares its maximum need. A request is granted only if, afterwards, some order exists in which every process can still get its remaining need and finish. |
| How is deadlock detected? | Detection | With single-instance resources, look for a cycle in the wait-for graph. With multiple instances, run a banker-style check on current allocations. Recovery means killing a process or preempting resources. |
| What do real operating systems do? | Practice | Most general-purpose kernels largely ignore deadlock for user resources (the ostrich approach) and leave it to applications, while kernel code follows strict lock ordering rules. |
def safe_order(available, allocation, maximum):
need = [[m - a for m, a in zip(mx, al)] for mx, al in zip(maximum, allocation)]
work = list(available)
finished = [False] * len(allocation)
order = []
progress = True
while progress:
progress = False
for p, done in enumerate(finished):
if not done and all(n <= w for n, w in zip(need[p], work)):
work = [w + a for w, a in zip(work, allocation[p])] # p finishes, frees its resources
finished[p] = True
order.append(f"P{p}")
progress = True
return order if all(finished) else None
available = [3, 3, 2]
allocation = [[0, 1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]]
maximum = [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]
print(safe_order(available, allocation, maximum))
# ['P1', 'P3', 'P4', 'P0', 'P2']File systems and I/O
- What is an inode? The on-disk record of a file's metadata (owner, permissions, size, timestamps) and where its data blocks are. The file name lives in the directory entry, not the inode.
- Hard link versus symbolic link? A hard link is another directory entry pointing to the same inode; the data stays until the last link is removed. A symbolic link is a small file holding a path, and it breaks if the target moves.
- What does journaling protect against? A crash in the middle of a multi-step update leaving the file system inconsistent. Changes (often only metadata) are written to a journal first and replayed after a crash.
- What is a file descriptor? A small integer index into a process's table of open files. Standard input, output and error are 0, 1 and 2, and they are inherited across
fork. - Polling, interrupts and DMA? Polling checks a device in a loop and wastes CPU. Interrupts let the device signal completion. DMA lets the device copy data to memory without the CPU touching every byte.
- Why does `write` returning not mean the data is on disk? It usually lands in the page cache first.
fsyncforces it to stable storage, which is what databases call before they report a commit. - Blocking, non-blocking and multiplexed I/O? Blocking calls sleep until data is ready. Non-blocking calls return immediately.
select,poll,epoll(Linux) andkqueue(BSD and macOS) let one thread wait on many descriptors, which is how event loops work.
Senior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Load average is high but CPU usage is low. What is going on? | Linux reading | On Linux, load counts tasks waiting in uninterruptible sleep too, usually on disk or network storage. Check I/O wait and blocked processes with vmstat or top before blaming the CPU. |
A server is slow and free shows almost no free memory. Is that the problem? | Memory accounting | Not by itself: Linux fills spare RAM with page cache and gives it back on demand. Look at available memory, swap activity and major page faults instead. |
| A process was killed with no error in its own logs. Where do you look? | OOM killer | The kernel log for an out-of-memory kill, then the process's memory limit (a container cgroup limit is a common cause) and its growth over time. |
| A program fails with "too many open files". What do you check? | Resource limits | The per-process file descriptor limit, and whether the program leaks descriptors by not closing sockets or files. Count them under /proc/<pid>/fd on Linux. |
| Why can a containerized app see all the host's CPUs but still be throttled? | Isolation | Containers share the host kernel; cgroups cap CPU time without hiding the cores, so runtimes that size thread pools from the visible core count can oversubscribe. |
| Why might adding threads make a CPU-bound job slower? | Scheduling cost | More runnable threads than cores means more context switches and cache misses for no extra parallelism. |
Fictional example
- Interviewer
- Walk me through what the operating system does when I type ./app and press Enter.
- Candidate
- The shell reads the line and calls fork, so the kernel creates a child process that shares the parent's pages copy-on-write. The child calls execve with the path. The kernel checks permissions, reads the executable's header, throws away the old address space and maps the new program's code and data segments, sets up a fresh stack with the arguments and environment, and if the binary is dynamically linked it starts the dynamic loader first to map shared libraries. Nothing is actually read into RAM yet beyond what is needed; the first instructions trigger page faults that load pages on demand. The new process enters the ready queue, and the scheduler eventually gives it a core. Meanwhile the parent shell called waitpid and sleeps. When the program exits, it becomes a zombie for a moment until the shell's wait collects its exit status, and then the prompt comes back.
How to prepare for OS interview questions
- Cover the syllabus onceProcesses and threads, scheduling, synchronization, deadlock, memory and paging, file systems and I/O. A standard OS textbook's chapter list is a good checklist.
- Practice the numeric problemsGantt charts for FCFS, SJF and round robin with waiting and turnaround times, page fault counts for FIFO, LRU and optimal, and a banker's algorithm safety check. Check your answers with small simulations like the ones above.
- Learn the comparisons as pairsProcess versus thread, mutex versus semaphore, paging versus segmentation, hard versus soft link, preemptive versus non-preemptive. Each pair usually comes as one question.
- Connect theory to LinuxRun
ps,top,vmstatandstraceon a real program once. Being able to say "this is the page cache" or "that is a system call" lifts an answer above the textbook. - Rehearse the "what happens when" walk-throughsRunning a program, a page fault, a system call and a context switch. Say each one aloud in under two minutes.
OS fundamentals are usually asked next to their neighbors. Multithreading interview questions takes synchronization into application code, DBMS interview questions covers transactions, locking and recovery in databases, and computer networks interview questions handles sockets and the protocol stack. For scheduling and graph algorithms in coding rounds, see algorithm interview questions.
OS answers are mostly explanations, so the useful practice is saying them aloud and checking them afterwards. Natively, an AI interview assistant for Mac and Windows, transcribes your mock fundamentals round, can draft an answer when you are stuck on a definition, and reads a scheduling or paging problem from a screenshot so you can compare its working with yours. With Pro or the free trial it can also use the résumé and job description you add, and every session's transcript and notes stay available for review.
Questions people ask
What are common OS interview questions?
Process versus thread, process states, context switches, scheduling algorithms, paging and virtual memory, page replacement, mutex versus semaphore, the four deadlock conditions, and what happens when a program runs.
What is the difference between a mutex and a semaphore?
A mutex has an owner and guards one resource; only the thread that locked it should unlock it. A counting semaphore is a counter any thread can signal, used to admit up to n users or to signal events.
What are the four conditions for deadlock?
Mutual exclusion, hold and wait, no preemption and circular wait. All four must hold at once, so breaking any one of them prevents deadlock.
What is virtual memory?
A mechanism that gives each process its own private address space, mapped to physical memory by page tables. Pages not in RAM are loaded on demand when a page fault occurs.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
