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.
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:
- Run programs. Load a program from disk, start it, and track it while it runs.
- Share the CPU. Decide which program runs on which core, and for how long.
- Hand out memory. Give each program its own private memory and stop programs reading each other's.
- Manage files and devices. Disks, network cards, keyboards, screens: programs ask the OS instead of talking to hardware directly.
- 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.
You call print. That is an ordinary function in user space.
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
RecursionErrorfirst. - 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.
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:
| Operation | Roughly |
|---|---|
| Read from CPU cache (L1) | 1 ns |
| Read from RAM | 100 ns |
| Read from an SSD | 100 µs (100,000 ns) |
| Network round trip in the same data centre | 0.5 ms |
| Network round trip across a continent | tens of ms |
Nanoseconds are hard to feel, so scale them up so that one L1 read takes one second:
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:
| fd | Name | Default |
|---|---|---|
| 0 | stdin (standard input) | the keyboard |
| 1 | stdout (standard output) | the terminal |
| 2 | stderr (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 $?# 127A 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).
Press Run (⌘ Enter) to see what happens.What does this print?
code = 137 print(code - 128)
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
KeyboardInterruptexception. - 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
killsends 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 linekill -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:
docker stop starts politely.
Match each situation to what is going on.
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.shRead -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.
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.
-rw-r-----. Which chmod number produces exactly that?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 onlyThree 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 whycdmust be built into the shell: a separatecdprogram could only change its own working directory. - A running server does not notice when you change a variable or a
.envfile. Its copy was taken when it started. Restart it.
export DEBUG=1 in terminal A, then start your app in terminal B. The app says DEBUG is not set. Why?- 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-xor the octal755.