Skip to content

51k · fork / wait / exit

Released Thu Dec 3, in class: posted here early

This is the README OSlings will give every student for 51k_fork_wait (oslings lesson shows it) when the exercise is released on Thu Dec 3. The starter code is not published here: it reaches you through OSlings, in class on the class network. Back to All Exercises.

Learn -> Understand -> Implement. So far the kernel ran one user program at a time. This exercise adds the three system calls that let a program start another program and collect its result - fork, exit, and wait - the trio at the heart of how every Unix shell launches commands. You write fork; exit and wait are given. To run more than one process, the kernel needs a scheduler, and you finally get to use the round-robin policy you wrote back in exercise 36k.

Learn

fork: one call that returns twice

fork() is the strangest and most important system call in Unix. It makes a near-exact copy of the running process - a new child process with its own copy of the parent's memory, registers, and open files - and then both processes return from the same fork() call and keep running. They are distinguished only by fork's return value:

        pid = fork();
       /            \
  parent            child
  pid = child's id  pid = 0

The parent gets the child's process id (a positive number); the child gets 0. That one difference is how a program knows which copy it is, and it branches accordingly:

    let pid = fork();
    if pid == 0 {
        // ...this is the child...
    } else {
        // ...this is the parent; pid is the child's id...
    }

It feels like magic, but the mechanism is exactly the machinery you already built. To copy a process you: allocate a new Proc (exercise 48k's allocproc), give it a fresh page table and copy the parent's user memory into it (a new helper, uvmcopy, built on the page-table walk from exercise 49k), and copy the parent's saved registers - its trapframe - so the child resumes at the very same instruction. Then you set the child's saved a0 to 0, and that is why fork returns 0 in the child.

exit and wait: finishing, and collecting the result

A child eventually calls exit(status). It cannot simply vanish - its parent may want to know how it finished - so exit leaves it a zombie: a slot in the process table that no longer runs but still holds the exit status. The parent's wait(&status) reaps the zombie: reads the status, frees the slot, and returns the child's pid; if no child has exited yet, wait blocks - gives up the CPU and tries again later. ("Zombie" is the real technical term.)

Both calls are given this time. The Understand list points you at exit_current (what exit does) and at sys_wait's reaping scan, which is fork in reverse.

The scheduler: running more than one process

With fork, there can suddenly be several runnable processes at once. The kernel needs a scheduler: a loop that repeatedly picks a runnable process, switches into it, and regains control when that process gives the CPU back - either by exiting or by blocking in wait. Switching in and out is swtch, which you wrote in exercise 35k; picking which process to run next is the round-robin policy you wrote in exercise 36k. This exercise finally wires them together to run real user processes:

  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

A process gives the CPU back in one of two ways, both given:

  • proc_yield (used by wait): mark myself Runnable again and swtch to the scheduler. When the scheduler picks me later, I resume right where I left off - this is how a blocked wait waits without freezing the machine.
  • exit_current (used by exit): mark myself a Zombie and swtch to the scheduler for good; the scheduler never switches back into a zombie.

All of the scheduler machinery - the loop, proc_yield, exit_current, the forkret entry point a fresh process starts at, and uvmcopy - is given, and so are exit and wait. Your job is the one syscall that puts all of it to work: fork.

Cooperative scheduling (why nothing is interrupted)

rv6's scheduler is cooperative: a process keeps the CPU until it chooses to give it up (by exiting, or by blocking in wait). Nothing forcibly preempts it. That keeps the behavior simple and predictable, which is exactly what you want while first learning fork/wait. (Real kernels also preempt on a timer so one process cannot hog the CPU; rv6 has the timer from exercise 44k, and turning it into preemption is a natural next step. This exercise doesn't take it; the extra-credit exercise 60k_preemption does.)

Understand

About 300 lines, read in this order. Skip whatever is not named here - the trampoline and usertrap in usermode.rs, the file calls in syscall.rs.

  1. rv6/src/proc.rs (~35 lines): the two new fields at the end of Proc - parent (who forked it) and xstate (the status it left on exit) - and has_children at the bottom. The given wait matches children on parent, so your fork must set it.
  2. rv6/src/usermode.rs (~130 lines): the scheduler. ready (a fresh process starts at forkret), run (the driver the shell and harness call), scheduler (the loop, using your RoundRobin), then the glue: forkret, proc_yield, exit_current. Skip the trampoline and usertrap - they are unchanged since exercise 48k.
  3. rv6/src/vm.rs (~45 lines): uvmcopy and copy_level at the bottom - the memory half of fork. They walk the page table exactly like free_pt above them, but copying instead of freeing.
  4. rv6/src/syscall.rs (~120 lines, mostly comments): the new numbers (fork = 1, exit = 2, wait = 3); sys_fork (yours - steps 1 and 2 are filled in, the doc comment walks through 3 to 6); sys_exit; and the given sys_wait - read its reaping scan, it is fork in reverse. Skip everything below sys_getpid.
  5. rv6/src/exec.rs (~10 lines): just the comments above forktest (forks one child) and forks2 (forks two). Skim the assembly if you want to see real fork/wait/exit calls.
  6. Optional, rv6/src/main.rs: fork_self_check, to see which [fail] line points at which step.

Control flow of run forktest:

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)

Implement

One handler, in rv6/src/syscall.rs:

  1. sys_fork: steps 1 and 2 - find the parent, allocate the child - are already written. You write steps 3 to 6: give the child a page table and a copy of the parent's memory with vm::uvmcopy (freeing the child if either fails); copy the parent's trapframe and set the child's a0 to 0; inherit the parent's open files and record the parent; make the child runnable and return its pid. About a dozen lines - the // IMPLEMENT comment walks through each step. Replace the placeholder lines (ending in proc::freeproc(child); -1); they only keep the stub from leaking process slots.

sys_wait is given: read the scan, it is fork in reverse. It finds a child only through the parent field your step 5 sets, so a wait that never returns, or returns -1 at once, usually means fork skipped that line.

Check your work:

oslings run 51k_fork_wait
# or
oslings watch

The harness runs a plain program (to check the scheduler), then forktest (one child), then forks2 (two children), checking the exit statuses that only correct fork + wait + exit can produce.

Then the payoff:

cd rv6 && cargo run        # boots to the rv6$ prompt

Try run forktest and watch both "parent" and "child" appear from what began as one program; then run forks2. You now have a kernel that runs a tree of processes - the last big piece before a real userland shell. (Exit QEMU with Ctrl-A then X.)

Stuck? oslings hint.