System calls, processes, scheduling, virtual memory, file descriptors, signals, and why containers are just processes.
Every program you run depends on the operating system. The OS decides which program gets the CPU, gives each one the illusion of having all of memory to itself, turns "open this file" into disk reads, and delivers the signal that tells your service to shut down. Most of the time it's invisible, until a container is OOMKilled, a server runs out of file descriptors, or a pod takes 30 seconds to stop.
This article covers the OS concepts that show up most in day-to-day backend and DevOps work, with Linux as the example.
The kernel is the core of the OS. It runs with full hardware privileges: it can touch any memory, talk to devices, and configure the CPU. Your programs run in user space with restricted privileges. They can't touch hardware or other processes' memory directly.
The boundary between them is the system call (syscall). Whenever a program needs something only the kernel can do, such as opening a file, sending a packet, starting a process or allocating memory, it makes a syscall. The CPU switches into kernel mode, the kernel does the work, and control returns to the program.
You can watch this with strace. Here's cat hello.txt, filtered to file operations:
$ strace -e trace=openat,read,write,close cat hello.txt
openat(AT_FDCWD, "hello.txt", O_RDONLY) = 3
read(3, "hello\n", 131072) = 6
write(1, "hello\n", 6) = 6
read(3, "", 131072) = 0
close(3) = 0
That's the whole program: open the file (the kernel returns file descriptor 3), read it, write to file descriptor 1 (standard output), see the end of the file, close it. Counting every syscall (strace -c), even cat makes about 44 of them, most of them loading shared libraries. Starting a Python interpreter that does nothing makes over 500.
Syscalls cost far more than ordinary function calls, roughly 100 ns to a few ยตs each. That's why buffered I/O exists: Python's print, C's stdio and Go's bufio collect many small writes into one big write syscall.
strace -p <pid> attached to a stuck process is one of the fastest debugging tools there is. It shows immediately whether the process is waiting on a network read, a lock (futex), or a file.
A process is a running program. It has its own virtual memory, its open file descriptors, its environment variables, a current directory, and at least one thread. Every process has a PID and a parent.
On Unix, new processes are created in two steps:
fork() clones the current process. Thanks to copy-on-write, memory pages are shared until one side writes to them, so forking is fast even for large processes.exec() replaces the clone's program with a different one.import os
import sys
pid = os.fork()
if pid == 0:
# child: replace this process with the `echo` program
os.execvp("echo", ["echo", f"hello from child, my parent is {os.getppid()}"])
else:
# parent: wait for the child and collect its exit status
_, status = os.waitpid(pid, 0)
print(f"parent {os.getpid()} saw child {pid} exit with code {os.waitstatus_to_exitcode(status)}")
sys.stdout.flush()
Your shell does exactly this for every command you type. Two related terms come up often:
0 means success, anything else means failure. When a process is killed by a signal, shells and container runtimes report 128 + signal number. Exit code 137 (128 + 9) means SIGKILL, usually from the OOM killer.wait() yet. It holds only a PID-table entry, but if zombies pile up you can run out of PIDs. More on this below for containers.A machine with 8 cores might be running 500 threads. The scheduler decides which thread runs on which core and for how long, typically in time slices of a few milliseconds. Switching from one thread to another (a context switch) means saving registers and loading another thread's state. It costs a few microseconds, plus the indirect cost of cold caches.
Linux used the Completely Fair Scheduler (CFS) from 2007, which tracks each thread's "virtual runtime" in a red-black tree and always runs the one that has had the least. Since kernel 6.6 (2023) it uses EEVDF, which builds on the same idea with better latency for interactive tasks.
What this means in practice:
uptime) is the average number of threads that are running or waiting to run. On Linux it also counts threads stuck in uninterruptible I/O. Compare it to your core count.Every process sees its own private virtual address space, as if it had all of memory to itself. The CPU's MMU translates virtual addresses to physical RAM using page tables that the kernel maintains, in units of pages (4 KiB by default on x86-64, with 2 MiB and 1 GiB "huge pages" available). A small cache called the TLB remembers recent translations, because walking the page tables on every memory access would be far too slow.
This indirection buys a lot:
malloc(1 GB) returns instantly. Physical pages are only assigned when you first touch them, which triggers a page fault.libc is loaded into physical memory once and mapped into every process.mmap): a file appears as memory, and the kernel loads pages on demand. Databases and search engines use this heavily.Two memory figures cause endless confusion:
| Metric | Meaning |
|---|---|
| VSZ / virtual size | All address space reserved, much of it never touched. Usually huge and mostly meaningless |
| RSS / resident set size | Physical RAM actually in use right now. This is what matters |
Because allocation is lazy, Linux by default overcommits: it lets processes reserve more memory than exists, betting they won't all use it. When the bet fails and RAM runs out, the OOM killer picks a process, usually the biggest, and sends it SIGKILL. In Kubernetes, a container that exceeds its memory limit is killed the same way, via its cgroup, and you see OOMKilled with exit code 137.
In Unix, "everything is a file": regular files, directories, pipes, sockets, terminals and devices are all accessed through file descriptors. A file descriptor is a small integer that indexes the process's table of open files. Every process starts with three:
| fd | Name | Default |
|---|---|---|
| 0 | stdin | Keyboard / input pipe |
| 1 | stdout | Terminal / output pipe |
| 2 | stderr | Terminal |
Every open file, socket and pipe uses a descriptor, and there's a per-process limit (ulimit -n, often 1024 by default on many systems). A busy server hitting "Too many open files" has either leaked descriptors (connections never closed) or needs a higher limit. You can inspect any process's descriptors through /proc:
import os
import socket
s = socket.socket() # opens a new file descriptor
f = open(__file__) # and another
for fd in sorted(os.listdir("/proc/self/fd"), key=int):
try:
print(fd, "โ", os.readlink(f"/proc/self/fd/{fd}"))
except FileNotFoundError:
pass # the descriptor used to list the directory itself
# 0 โ /dev/pts/0 1 โ /dev/pts/0 2 โ /dev/pts/0 3 โ socket:[โฆ] 4 โ /path/to/script.py โฆ
s.close(); f.close()
Two more file system details that matter for data safety:
fsync: write() usually returns once the data is in the kernel's page cache in RAM, before it reaches the disk. If the machine loses power, it's gone. Databases call fsync() to force data to stable storage before confirming a commit. That's the "D" in ACID, and one reason database writes cost more than you'd expect.Signals are asynchronous notifications sent to a process:
| Signal | Number | Default | Can be caught? | Typical source |
|---|---|---|---|---|
SIGINT |
2 | Terminate | Yes | Ctrl+C |
SIGTERM |
15 | Terminate | Yes | kill, docker stop, Kubernetes pod shutdown |
SIGKILL |
9 | Terminate | No | kill -9, OOM killer, end of the grace period |
SIGHUP |
1 | Terminate | Yes | Terminal closed; often reused to mean "reload config" (nginx) |
SIGCHLD |
17 | Ignore | Yes | A child process exited |
SIGTERM is a polite request to stop. SIGKILL can't be caught, blocked or cleaned up after. Kubernetes stops a pod by sending SIGTERM, waiting terminationGracePeriodSeconds (30 by default), then sending SIGKILL. A service should handle SIGTERM by finishing in-flight requests and exiting cleanly:
import signal
import time
stopping = False
def on_sigterm(signum, frame):
global stopping
print("SIGTERM received: finishing in-flight work, then exiting")
stopping = True
signal.signal(signal.SIGTERM, on_sigterm)
while not stopping:
time.sleep(0.5) # stand-in for serving requests
print("clean shutdown")
Inside a container, your application often runs as PID 1, which is special in two ways:
SIGTERM, the signal is ignored, so the container sits there until it's SIGKILLed after the full grace period. That's the classic "why does my pod take 30 seconds to stop?"Fixes: handle SIGTERM in your app, run the app through a tiny init process (docker run --init, tini, dumb-init), and use the exec form in Dockerfiles (CMD ["python", "app.py"], not CMD python app.py). The shell form starts /bin/sh as PID 1, and it doesn't forward signals to your app.
A container is not a lightweight virtual machine. It's an ordinary Linux process with two kernel features applied:
pid), network interfaces (net), mount points (mnt), hostname (uts), users (user) and IPC.You can create a PID namespace yourself, without Docker:
$ unshare --user --map-root-user --pid --fork --mount-proc ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 8352 4168 ? R 17:51 0:00 ps aux
Inside the new namespace, ps sees only itself, as PID 1, and believes it's root. That's the core of what Docker and Kubernetes do, plus layered file systems for the image and cgroups for resource limits. It also explains why containers share the host's kernel, and why a kernel vulnerability can affect every container on a host.
| Symptom | First tools to reach for |
|---|---|
| Process is stuck | strace -p PID, cat /proc/PID/stack (as root), py-spy dump for Python |
| High CPU | top / htop, perf top, pidstat 1 |
| Memory growth / OOM | free -h, RSS in ps, dmesg \| grep -i oom, kubectl describe pod |
| "Too many open files" | ls /proc/PID/fd \| wc -l, ulimit -n, lsof -p PID |
| Disk full but files deleted | lsof +L1 (open but deleted files), df -h vs du -sh |
| Slow I/O | iostat -x 1, iotop |
| Pod slow to stop | Does the app handle SIGTERM? Is it running as PID 1 via a shell? |
The OS is the layer every abstraction above it relies on. Knowing what processes, memory, file descriptors and signals actually are turns many production mysteries into quick diagnoses. For the hardware underneath, see How Computers Actually Run Your Code. For how containers become a cluster, see the Kubernetes Internals tutorial.