← Week 15 page
# Week 15 · Thursday talk ## `fork`, `wait`, and `exec` CS 326 Operating Systems · Thursday, December 3 - [Prep: fork, wait, and exec](../prep/15-cs326-2026-12-03-prep-fork-and-exec/) - READMEs: [`51k_fork_wait`](../assignments/exercises/51k_fork_wait/) · [`52k_userland`](../assignments/exercises/52k_userland/) - [Week 15 videos](../videos/week15/): 5 to 7 are today's - Reading: [Week 15 · Essentials](../lectures/15-cs326-2026-12-01-fork-wait-and-the-user-shell/#essentials)
A 15-minute talk, then the exercises.
oslings submit
before you leave.
Notes: **0:00–1:00 · 1 min.** Today the kernel learns to run a *tree* of processes (`51k`), then `exec` becomes a system call and the shell moves out of the kernel into user mode (`52k`). Both READMEs are in OSlings now, and on the site from the links here. **Minute plan** (15 minutes) | Min | Slide | |---|---| | 0:00–1:00 | title | | 1:00–3:00 | 51k-fork | | 3:00–5:00 | 51k-zombie | | 5:00–7:00 | 51k-scheduler | | 7:00–8:30 | 51k-write | | 8:30–10:30 | 52k-exec | | 10:30–12:00 | 52k-no-return | | 12:00–13:30 | 52k-shell | | 13:30–15:00 | 52k-write | **Cut order** if behind: 52k-shell's interrupt note first, then 51k-scheduler down to one minute (read the loop, say "cooperative"). Never cut the two "What you write today" slides. - **Q:** "Which do I start with?" `51k_fork_wait`: `52k` builds on `fork` and `wait`. Done is `oslings run` green, then `oslings submit` before you leave. --- ## `51k` · `fork`: one call that returns twice `fork()` makes a near-exact **copy** of the running process: a **child** with its own copy of the parent's memory, registers, and open files. Both return from the same call: ```text pid = fork(); / \ parent child pid = child's id pid = 0 ``` ```rust let pid = fork(); if pid == 0 { // ...this is the child... } else { // ...this is the parent; pid is the child's id... } ``` Notes: **1:00–3:00 · 2 min.** - The strangest and most important system call in Unix: both processes return from one `fork()` and keep running, told apart only by its return value. The parent gets the child's pid, a positive number; the child gets 0, and no process has pid 0. - Why 0: the child gets a copy of the parent's saved registers, its trapframe, so it resumes at the very same instruction, and the kernel sets the child's saved `a0` to 0. With no free slot or no memory, `fork` copies nothing and returns -1. - **Q:** "Which one runs first?" In rv6, the parent: nothing takes the CPU from it until it waits or exits. --- ## `exit` leaves a zombie; `wait` reaps it A child that calls `exit(status)` cannot simply vanish: its parent may want to know *how* it finished. It becomes a **zombie**, a slot that no longer runs but still holds the status, until the parent's `wait` **reaps** it. `run forktest`: ```text parent: fork() ──▶ sys_fork: copy me into a child, child's a0 = 0 <- YOU (parent gets child's pid; child gets 0 and runs the child branch) parent: writes "parent", then wait(&s) ──▶ sys_wait: no zombie child yet ──▶ proc_yield (block) (given) scheduler: runs the child ──▶ child writes "child", exit(7) [zombie] scheduler: runs the parent again ──▶ sys_wait reaps the zombie, s = 7, returns the child's pid (given) parent: exit(7 + 10 = 17) ``` Notes: **3:00–5:00 · 2 min.** - Reaping is three things: read the status, free the slot, return the child's pid. If no child has exited yet, `wait` **blocks**: it gives up the CPU and tries again later. A caller with no children at all gets -1 at once. ("Zombie" is the real technical term.) - Walk the trace top to bottom: one program became two, the child's 7 reached the parent, and the parent exits 17. `exit` and `wait` are both given; read `exit_current` and `sys_wait`'s reaping scan, which is `fork` in reverse. - **Q:** "What if the parent never calls `wait`?" The zombie keeps its slot until the run ends. On Linux, `ps` shows it as `Z` until its parent exits and `init` reaps it. --- ## The scheduler: more than one process With `fork`, several processes can be **runnable** at once. The given loop finally wires your `36k` policy to your `35k` switch: ```text scheduler loop: pick a Runnable process (RoundRobin::pick_next - your exercise 36k!) swtch into it (your exercise 35k swtch) ...it runs until it yields (wait) or exits... swtch back to the scheduler repeat, until the first process (and its whole tree) has finished ``` rv6 is **cooperative**: a process keeps the CPU until it *chooses* to give it up, by exiting or by blocking in `wait`. Notes: **5:00–7:00 · 2 min.** - Two ways back to the scheduler, both given. `proc_yield`, used by `wait`: mark myself Runnable and `swtch` to the scheduler; when picked later, I resume right where I left off, so a blocked `wait` never freezes the machine. `exit_current`, used by `exit`: mark myself a Zombie and `swtch` away for good; the scheduler never switches back into a zombie. - A fresh process starts at `forkret`, also given. Nothing preempts, which is why `parent` prints before `child` in `forktest`. - **Q:** "Why not preempt on the timer?" Cooperative keeps the behavior simple and predictable while you first learn fork and wait. The `44k` timer is there; turning it into preemption is extra credit `60k_preemption`, released Friday. --- ## What you write today · `51k` **`sys_fork`**, in `rv6/src/syscall.rs`. Steps 1–2 are written; yours: 3. a page table and a copy of the parent's memory (`vm::uvmcopy`); free the child if either fails 4. copy the parent's trapframe; the child's `a0` = 0 5. inherit the open files; record the parent 6. make the child runnable; return its pid Given: `exit`, `wait`. Check: `oslings run 51k_fork_wait` Notes: **7:00–8:30 · 1.5 min.** - About a dozen lines; the `// IMPLEMENT` comment walks through each step. Replace the stub's placeholder lines, the ones ending in `proc::freeproc(child); -1`: they only keep it from leaking process slots. - Step 5 matters to the given code: `sys_wait` matches children on the `parent` field, so your `fork` must set it. The harness runs a plain program (to check the scheduler), then `forktest` (one child) and `forks2` (two), checking exit statuses only a correct fork, wait and exit produce. Then `cd rv6 && cargo run`, `run forktest`, `run forks2`; leave QEMU with Ctrl-A, then X. - **Q:** "Where do I start reading?" The README's Understand list, about 300 lines in order: `proc.rs`'s new fields, the scheduler in `usermode.rs`, `uvmcopy` in `vm.rs`, then `syscall.rs` and the `forktest` comments in `exec.rs`. --- ## `52k` · `exec`: new program, same process A copy of the shell is still the shell. To run `ls`, the copy has to *become* `ls`: ```text before exec("ls", argv) after pid, open files ──▶ the same pid, the same open files sh's code, data, stack ──▶ ls's code, data, stack the old page table ──▶ a brand-new page table ``` `exec` builds a brand-new page table holding the new program, swaps it in for the old one, and starts the program at its first instruction. Notes: **8:30–10:30 · 2 min.** - `fork` answers "make another process"; `exec` answers "run this program in it". The pieces are yours from `49k`; `52k` gathers three of them into one given helper, `build_addrspace`. The swap points the process at the new page table, repoints its trapframe at the new program's first instruction and stack, and frees the old page table. - Freeing the old memory under a running program is safe: a system call runs on the **kernel's** page table, so while the swap runs, the old user page table is just data. - **Q:** "So where does the new program actually start?" `usertrapret` sets `sepc` from the trapframe's `epc`, `satp` from the process's page table, and `sp` from the trapframe, so repointing the page table and the trapframe is all it takes to "jump" into the new program. --- ## Only a failed `exec` returns On success there is **no code to return to**: the instruction after the `exec` call was just thrown away. ```text program A calls exec("B", ...) | | success: A's memory is replaced by B; we resume in B at its start. | A's next instruction is gone; exec does not return. v program B runs ────────────▶ (A is gone; only B remains, same pid) ...OR, on failure (no such program B): exec returns -1, and A keeps running its own code. ``` Notes: **10:30–12:00 · 1.5 min.** - This is the strangest thing about `exec`, and the key to it. A failure returns -1 to a caller that is still its old self, so it can react: read every line after an `exec` as its failure path. - The harness checks exactly these cases: `execself` (exec does not return), `exectest` (fork, exec, wait) and `execfail` (a failed exec returns -1 and the caller lives on). - **Q:** "Then how does the shell learn how the command went?" Not from `exec`: its child called that. The shell learns from `wait`, when the child, now the new program, exits. --- ## The shell leaves the kernel Every Unix shell runs a command the same way: ```rust let pid = fork(); // 1. make a child (a copy of the shell) if pid == 0 { exec("ls", argv); // 2. the child BECOMES `ls` // exec never returns on success: the child is `ls` now } else { wait(&status); // 3. the shell waits for `ls` to finish } ``` New today: `sh`, a **user program** that does just this, with only `read`, `write`, `fork`, `exec`, `wait` and `exit`. At `rv6$`, type `run sh`; the prompt becomes `$`. Notes: **12:00–13:30 · 1.5 min.** - Since `46k` the shell has lived in the kernel, `shell.rs`, calling the filesystem directly. In Unix the shell is an ordinary user program that can only ask through system calls. `sh` prints a prompt, reads a line, splits it into words, forks; the child execs, the parent waits. The kernel shell is still underneath: `exit` at `$ ` brings back `rv6$`. - One wrinkle, given: `sh`'s `read` blocks until a key arrives as a UART interrupt, but the CPU turns interrupts off on entry to the kernel. So `sys_read`, the one call that blocks on the console, turns them back on, and only there, so deeper calls like `exec` keep a quiet, shallow kernel stack. - **Q:** "Why is `exit` built in, not a program?" A program named `exit` would run in the child and end only the child. Only the shell can end the shell. --- ## What you write today · `52k` **`exec_into`**, in `rv6/src/exec.rs`: the swap. 1. build the new address space with `build_addrspace`; use `?` so a failure leaves the old program untouched 2. remember the old page table 3. install the new one 4. point the trapframe at the new program:
`USER_CODE`, new `sp`, `a0 = argc`, `a1 = argv` 5. free the old page table 6. return argc Check: `oslings run 52k_userland` Notes: **13:30–15:00 · 1.5 min.** - The `// IMPLEMENT` comment walks through the six steps, and `build_addrspace` is given. The Understand list calls the given `build_process` the model: the same swap, for a fresh process. It also points at `sys_exec` and `fetch_argv`, which copy the path and argument strings out of user memory, then call your `exec_into`. - The payoff: `cd rv6 && cargo run`, then `run sh` at `rv6$`, and at `$ ` try `hello`, `echo hi there`, `forktest`, then `exit`. Every one ran as a user program, launched by a shell that is itself a user program: the finish line of the course. - **Q:** "When am I done?" When `oslings run` is green, then `oslings submit` before you leave. Not green? Submit anyway; the tests that pass earn their share.