Skip to content

Lesson 4 of 18How software works

What the Operating System Does

Processes, memory, standard streams, exit codes, signals, permissions and environment variables: the OS ideas behind everyday errors.

16 min read0/4 questions

Your first week on a team, you will probably meet errors like these: a deploy fails with exit code 137, a script says Permission denied when you try to run it, the server you just stopped is still holding its port, and a variable you set in one terminal is missing in another. Each one comes from the operating system (OS), the program that runs every other program. In How Code Runs you saw the OS as one layer in the stack, between your runtime and the hardware. This lesson opens that layer up. You do not need to build an OS, but you do need to know what it is doing for you, because those errors are the OS telling you something precise.

The operating system's jobs

macOS, Linux and Windows look very different, but they all do the same five jobs:

  1. Run programs. Load a program from disk, start it, and track it while it runs.
  2. Share the CPU. Decide which program runs on which core, and for how long.
  3. Hand out memory. Give each program its own private memory and stop programs reading each other's.
  4. Manage files and devices. Disks, network cards, keyboards, screens: programs ask the OS instead of talking to hardware directly.
  5. Enforce users and permissions. Decide who may read, change or run what.

The core of the OS is the kernel. It runs in a privileged mode with full control of the hardware. Your programs run in user space, with no direct access. When your code opens a file, sends data over the network, or starts another program, it makes a system call: a request to the kernel. open, read, write, fork and kill are real system call names. Every print() you have ever written ends in a write system call.

What happens when Python prints
  1. print("hi")your code
  2. Python runtimeturns the text into bytes, buffers them
  3. write(1, "hi\n")system call into the kernel
  4. Kernelchecks permission, sends bytes to the terminal

You call print. That is an ordinary function in user space.

1/4

Programs, processes and threads

A program is a file on disk, like /usr/bin/python3. A process is a running copy of a program, with its own memory, its own open files and its own ID number, the PID. Run python3 in two terminals and you have one program and two processes.

Every process (except the very first one) was started by another process, its parent. When you type a command, your shell is the parent and the command is the child. The parent's PID is the PPID.

ps aux                    # every process on the machine (works on macOS and Linux)ps -o pid,ppid,command    # just the ones in this terminal, with parent IDs#   PID  PPID COMMAND# 53492  2659 -zsh# 53493 53492 python3 server.py      <- its parent is the shell abovepgrep -fl server.py       # find processes by nametop                       # live view, sorted by CPU (press q to quit)

top exists on both systems; on Linux many people install htop for a friendlier view. macOS has the Activity Monitor app and Windows has Task Manager, which show the same information.

A thread is a separate line of execution inside a process. All threads in one process share its memory, which makes them cheap to create and fast to share data, but also lets them trip over each other. Processes do not share memory unless they ask to, so a crash in one process cannot corrupt another. That is the trade-off at the heart of a classic interview question, answered at the end.

Sharing the CPU

A laptop might have 8 or 10 cores and run 500 processes. The OS scheduler makes this work by giving each runnable thread a short slice of time on a core, often a few milliseconds, then pausing it and switching to another. Swapping one thread out and another in is a context switch. It happens thousands of times a second, so everything looks like it runs at once.

Most processes are not running most of the time. They are waiting: for a key press, a disk read, a network reply. A waiting process uses no CPU. That is why a web server with thousands of open connections can be nearly idle, and why "slow" code is often waiting on I/O rather than computing.

Memory: virtual memory, stack and heap

Each process gets its own virtual address space: it believes it has a huge, private range of memory starting near zero. The OS and the CPU translate those virtual addresses to real RAM behind the scenes, in chunks called pages. Two processes can both use address 0x1000 and never collide, and one process cannot read another's memory. This is a big part of why one crashing app does not take down your whole machine.

Inside its address space, a program uses memory in two main ways:

  • The stack holds function calls. Each call pushes a frame with its local variables and where to return; each return pops it. It is fast and cleaned up automatically, but small (often around 8 MB per thread). Recursion that never stops fills it, which is a stack overflow. Python guards against this with a recursion limit and raises RecursionError first.
  • The heap holds everything that must outlive a single call: objects, lists, strings, anything whose size is decided at run time. It is large but managed: in Python and JavaScript a garbage collector frees what nothing refers to any more.
Python
import sys def countdown(n): return 0 if n == 0 else countdown(n - 1) # one stack frame per call print("recursion limit:", sys.getrecursionlimit())print(countdown(500))try: countdown(100_000)except RecursionError as e: print("RecursionError:", e)
Output
Press Run (⌘ Enter) to see what happens.

What if the machine runs out of RAM? First the OS moves pages that have not been used for a while out to disk, called swap (macOS also compresses memory). Everything slows down dramatically, because disk is far slower than RAM. If memory still runs out, Linux's OOM killer ("out of memory") picks a process, usually the biggest, and kills it outright. In containers this is more common still: each container has a memory limit, and going over it gets the process killed immediately. Remember that, because it is the story behind exit code 137 below.

How slow is "slow"?

Seniors carry rough numbers in their heads, because they explain why caching and batching matter. These are orders of magnitude, not exact figures:

OperationRoughly
Read from CPU cache (L1)1 ns
Read from RAM100 ns
Read from an SSD100 µs (100,000 ns)
Network round trip in the same data centre0.5 ms
Network round trip across a continenttens of ms

Nanoseconds are hard to feel, so scale them up so that one L1 read takes one second:

Python
ladder = [ ("L1 cache read", 1), ("RAM read", 100), ("SSD read", 100_000), ("Same-datacentre round trip", 500_000), ("Cross-continent round trip", 80_000_000),] def human(seconds): for unit, size in [("years", 31_536_000), ("days", 86_400), ("hours", 3_600), ("minutes", 60)]: if seconds >= size: return f"{seconds / size:.1f} {unit}" return f"{seconds} second" + ("" if seconds == 1 else "s") for name, ns in ladder: print(f"{name:<28} {human(ns)}")
Output
Press Run (⌘ Enter) to see what happens.

If reading RAM takes about a minute and a half, one call to a database across the country takes years. That single picture explains why one query inside a loop over 1,000 items is a disaster, and one query for all 1,000 is fine.

Standard streams and exit codes

Every process starts with three open channels, numbered with small integers called file descriptors:

fdNameDefault
0stdin (standard input)the keyboard
1stdout (standard output)the terminal
2stderr (standard error)the terminal

Programs write normal results to stdout and errors and logs to stderr. Both appear in your terminal, but they are separate, so you can send them to different places. In The Terminal you used > and |; they work on fd 1. The number in front picks a different stream:

python3 report.py > out.txt            # stdout to a file, errors still on screenpython3 report.py 2> errors.txt        # only stderr to a filepython3 report.py > all.txt 2>&1       # stderr goes wherever stdout goespython3 report.py 2> /dev/null        # throw errors away (use with care)

When a process ends, it hands its parent a number from 0 to 255: the exit code (or exit status). 0 means success. Anything else means failure. Your shell keeps the last one in $?, and every CI system, Docker and Kubernetes read it to decide whether a step passed.

ls /nope# ls: /nope: No such file or directoryecho $?# 1                     (GNU ls on Linux uses 2 here: codes vary by program)nosuchcmd# zsh: command not found: nosuchcmdecho $?# 127

A few codes are worth memorising, because they come from the shell and the OS rather than from the program:

  • 1: general failure. Python exits with 1 on an uncaught exception.
  • 2: often "bad command-line usage".
  • 126: found but not executable (usually a permissions problem).
  • 127: command not found (a typo, or not on PATH).
  • 128 + N: killed by signal number N. So 130 is 128 + 2 (Ctrl+C), 137 is 128 + 9 (SIGKILL), 143 is 128 + 15 (SIGTERM).
Python
SIGNALS = {2: "SIGINT (Ctrl+C)", 9: "SIGKILL (often out of memory)", 15: "SIGTERM (asked to stop)"} def explain(code): if code == 0: return "success" if code == 126: return "found but not executable: check permissions" if code == 127: return "command not found: check spelling and PATH" if code > 128: n = code - 128 return f"killed by signal {n}: {SIGNALS.get(n, 'another signal')}" return "the program reported a failure: read its stderr" for code in [0, 1, 127, 130, 137, 143]: print(code, "->", explain(code))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

code = 137
print(code - 128)
Need a nudge? Hints walk you through it.

Signals

A signal is a small message the OS delivers to a process, usually meaning "stop" in some form. Three matter most:

  • SIGINT (2) is what Ctrl+C sends. It means "the user wants you to stop". Python turns it into a KeyboardInterrupt exception.
  • SIGTERM (15) is a polite request to shut down. A well-written server catches it, finishes the requests it is handling, closes database connections, and exits cleanly. It is what kill sends by default, and what Docker and Kubernetes send first.
  • SIGKILL (9) cannot be caught or ignored. The kernel removes the process on the spot: no cleanup, no flushing of buffers, no "saving your work". The OOM killer uses it.
kill 53493          # sends SIGTERM: please stopkill -9 53493       # sends SIGKILL: stop now, no cleanuppkill -f server.py  # signal processes by matching their command line

kill -9 works, but it is a last resort. A process killed that way can leave half-written files, lock files that make the next start fail, or unfinished transactions. Try plain kill first and give it a few seconds.

Here is what happens when a container platform stops your app, for example during a deploy:

How docker stop shuts down a container
DockerKernelYour serversend SIGTERMSIGTERMfinish requests, close DBwait 10 secondssend SIGKILLexit code 137

docker stop starts politely.

1/6
Match the pairs0/5 matched

Match each situation to what is going on.

Choose an item, then its match on the other side.

Users and file permissions

Every file has an owner (a user), a group, and three sets of permissions: for the owner, for the group, and for everyone else ("other"). ls -l shows them:

ls -l deploy.sh# -rw-r--r--  1 sam   staff  0 Oct 22 11:19 deploy.sh./deploy.sh# zsh: permission denied: ./deploy.shchmod +x deploy.shls -l deploy.sh# -rwxr-xr-x  1 sam   staff  0 Oct 22 11:19 deploy.sh

Read -rwxr-xr-x in four pieces. The first character is the type: - for a file, d for a directory, l for a link. Then three groups of three: owner rwx, group r-x, other r-x. r is read, w is write, x is execute (for a directory, x means you may enter it). A - means "not allowed".

Each group of three is also one octal digit, which is why you saw octal in the previous lesson: r is 4, w is 2, x is 1, and you add them up. rwx is 7, r-x is 5, r-- is 4. So chmod 755 means rwxr-xr-x and chmod 600 means rw-------, only the owner can read or write. That last one is what SSH demands for private keys.

Python
def perms(mode): out = "" for digit in f"{mode:03o}": d = int(digit) out += ("r" if d & 4 else "-") + ("w" if d & 2 else "-") + ("x" if d & 1 else "-") return out for mode in [0o755, 0o644, 0o600, 0o700]: print(oct(mode), perms(mode))
Output
Press Run (⌘ Enter) to see what happens.

chown user:group file changes the owner (you usually need admin rights). To see a file's permissions as a number, use stat -f '%Lp' file on macOS or stat -c '%a' file on Linux.

The all-powerful user is root. sudo runs one command as root. Use it for system changes like installing packages with apt, but not as a reflex. In particular, never run sudo pip install or sudo npm install -g: they write root-owned files into places your normal user then cannot update, and they let any install script run with full control of your machine. If an install fails with a permission error, the fix is a virtual environment, a version manager, or a correctly configured install folder, as in Setting Up Your Machine.

Quick check
A file shows -rw-r-----. Which chmod number produces exactly that?
Need a nudge? A hint rules out a wrong answer.

Environment variables belong to a process

In The Terminal you set variables with export. Here is what is really happening: every process has its own private copy of its environment. When a process starts a child, the child gets a copy of the parent's exported variables at that moment. After that, they are independent.

export API_URL=http://localhost:8000python3 -c 'import os; print(os.environ.get("API_URL"))'# http://localhost:8000          the child inherited itLOCAL=onlypython3 -c 'import os; print(os.environ.get("LOCAL"))'# None                           not exported, so not passed onMODE=test python3 -c 'import os; print(os.environ.get("MODE"))'# test                           set for this one command only

Three everyday consequences follow from "a copy, passed down, never up":

  • A new terminal does not see a variable you exported in another one. They are separate shell processes with separate copies. That is why permanent settings go in ~/.zshrc (macOS default) or ~/.bashrc (most Linux), which every new shell runs at start.
  • A child cannot change its parent. A Python script that sets os.environ["X"] changes only its own copy; your shell never sees it. That is also why cd must be built into the shell: a separate cd program could only change its own working directory.
  • A running server does not notice when you change a variable or a .env file. Its copy was taken when it started. Restart it.
Quick check
You run export DEBUG=1 in terminal A, then start your app in terminal B. The app says DEBUG is not set. Why?
Need a nudge? A hint rules out a wrong answer.
Key terms
kernel
The core of the operating system. It controls the hardware, and programs ask it for things through system calls.
process
A running instance of a program with its own memory and PID. A thread runs inside a process and shares its memory.
virtual memory
Each process sees its own private address space, which the OS maps onto real RAM in pages.
stdin / stdout / stderr
The three standard streams every process starts with: file descriptors 0, 1 and 2.
exit code
The number a process returns when it ends. 0 is success; 128 + N means killed by signal N.
signal
A message from the OS to a process. SIGINT is Ctrl+C, SIGTERM asks politely, SIGKILL cannot be caught.
file permissions
Read, write and execute rights for owner, group and other, shown as rwxr-xr-x or the octal 755.