mcruz.me
← All writing

Implementing a Unix Shell in C

Two copies of a program are running. What happens when you press Control-Z? A shell lab trace follows the signal from the terminal to the job table.

On this page

Start two copies of the same program, leave one in the background, and press Control-Z while the other is running in the foreground. Which copy should stop? How does the shell know when it can print another prompt? These questions are the core of my tiny Unix shell. The CS:APP Shell Lab gave me a driver, helper programs, and traces that make job control observable. My implementation connects the commands at the prompt to the process groups and signals underneath. Shell Lab files.

What the shell remembers

Each entry in the job table holds a process ID, a shell-assigned job number, the original command line, and a state. The process ID is how the shell refers to a child when talking to the kernel. The job number is the short handle you can type as %1 or %2. Keeping the original text lets jobs show that two instances of the same executable came from different commands. At most one entry should be in the foreground. Other entries can be running in the background or stopped. Job states and records.

When I enter ./myspin 4 &, the parser removes the final ampersand from the argument list and reports a background command. For an external command the shell forks, and the child calls setpgid(0, 0) to become the leader of a new process group. It then passes the executable path, arguments, and inherited environment to execve. This explains why the traces spell out paths such as ./myspin and /bin/echo. The implementation passes the first argument directly to the kernel. Launching a command.

Following two jobs through a stop and resume

The ninth trace starts one helper for four seconds in the background and another for five seconds in the foreground. The helper sleeps in one-second increments. After two seconds, the driver sends the shell the stop signal an interactive user would normally produce with Control-Z. It then asks for the job list, resumes job 2 in the background, and asks for the list again. Trace 9.

The foreground lookup is what makes that sequence work. The stop handler finds job 2's process ID and passes its negative to kill. In this call, a negative ID addresses the process group. The background helper belongs to a different group and keeps running. The first listing in the reference transcript shows job 1 running and job 2 stopped. On bg %2, the shell looks up the entry by its job number, sends the group SIGCONT, and records the background state. The second listing shows both jobs running. Their process IDs stay the same throughout. Reference transcript.

When a foreground job has two processes

The two-helper example still leaves room for a subtle mistake. If the stop handler sent a signal to just the individual foreground PID, the first listing would look right. Each copy of myspin consists of a single process. The twelfth trace changes that detail. It launches ./mysplit 4, which forks its own child. The child sleeps in a loop while the original process waits for it. The shell still creates exactly one job-table entry because it directly launched only the original process. Both processes inherit membership in the foreground job's group. Two-process helper.

Trace 12 sends the stop signal two seconds in and then requests both jobs and /bin/ps a. Those commands observe different things. My shell can report its one entry as stopped as soon as the stop handler updates the table. The ps output observes the individual processes. In the saved reference transcript there are two entries for ./mysplit 4, and both have status T, meaning stopped. If the shell had signaled just the leader, the child could have continued sleeping while the job list still looked correct. Group-stop trace. Reference process listing.

Resuming uses the same group identity in the opposite direction. With fg %1, the builtin finds job 1, sets its table state to foreground, sends SIGCONT to the group, and enters waitfg. Both the waiting parent and the sleeping child can resume. The child eventually exits, its parent collects it and exits in turn, and the shell collects the parent. With bg %1, the group likewise resumes, but the shell leaves the prompt available for another command. Looking at which process waits for which child explains why the terminal sees a single job throughout that sequence. Resume and foreground-wait code.

The race between launch and bookkeeping

When a child exits, the kernel can deliver SIGCHLD while the parent is still processing the launch. My handler calls waitpid in a loop, asking for any child whose status is ready. WNOHANG lets the loop finish when there is nothing left to collect. WUNTRACED also reports stopped children. An ordinary exit removes the corresponding job from the table. Collecting child status.

Reading the launch code again, I can see a timing hole. The parent blocks signals before the fork, but unblocks them before adding the new job. A short-lived child can finish in that interval. The handler can collect its exit and find no record to remove. Then the parent inserts a job whose process has already gone. A foreground wait can keep checking that stale entry. Registering the child while the signals are still blocked would give the handler a consistent table when delivery resumes. Signal ordering in the parent.

Signal reporting has a similar gap between intent and observation. The interrupt handler prints a termination message and deletes the job immediately after forwarding SIGINT. Forwarding requests an action from another process. The status returned by waitpid is where the shell can learn how that process actually ended. A program can handle an interrupt itself, for example. The implementation also prints fixed signal numbers in parts of the status handler. Reading the terminating or stopping signal from the returned status would distinguish an interrupt from other reasons a child was stopped or killed. Signal forwarding and status reporting.

The traces capture what a user should see, down to which job stays running. They also explain why the same transcript can look right while an ordering bug survives. A sleeping helper leaves ample time to register the child. A command such as /bin/true can exit while the parent is still returning from fork. The first case tells me where Control-Z went. The second makes me ask whether the shell remembered the job in time to forget it.