Lesson 2 of 7
Processes
A is a running program plus everything it owns, such as its and open files. You'll learn how processes are created, inspected and stopped.
A program is a file on disk; a process is that program running. Each process gets its own virtual address space (it thinks it has all of memory to itself), its own file descriptor table, an ID (PID), an owner, and a parent. Chrome with 40 tabs is dozens of processes on purpose — one tab crashing can't corrupt another.
ps aux | head # snapshot of all processes
# USER PID %CPU %MEM ... COMMAND
# noah 4312 12.0 2.3 ... firefox
pstree | head # processes form a family tree
echo $$ # PID of your shell
kill 4312 # ask process 4312 to exit (SIGTERM)
kill -9 4312 # force it, no cleanup (SIGKILL)
# A process's memory layout, roughly:
# [ code | globals | heap -> ... <- stack ]
# heap grows up (malloc/new), stack grows down (calls)# Creating processes — the Unix way is fork + exec:
import os, subprocess
# High level (what you'll actually use):
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)
# What's underneath: fork() clones the current process;
# exec() replaces the clone's program with a new one.
pid = os.fork()
if pid == 0:
os.execvp("echo", ["echo", "I am the child"])
else:
os.waitpid(pid, 0) # parent waits for child to finish
print("child done")Common question
Are a process and a program the same thing?
A process is a program that is running, plus everything the kernel tracks about it: an address space, a table of open files, a user, a scheduling state and a process ID. Keeping processes apart is what stops one crashing program from taking the whole machine with it, and only the kernel can connect them.
The everyday facts of systems programming follow from this: fork and exec create and replace processes; and sockets carry data between them; exit codes and signals report and control how they end; and choosing between processes and threads is choosing between isolation and shared memory.
Source: The kernel gives each process its own page table, which maps its addresses to physical memory. That is what keeps one running program apart from another.
Common mix-ups
Each of these sounds reasonable. Think about why it is wrong, then open the explanation.
A program is what runs, so running one is the same as being a process.
A process can read another process's memory if it knows the address.
Threads are lightweight processes and behave the same way.
Tip: use the ← and → keys to move between lessons.