Projects / Unix shell / Phase 4
Phase 4 of 4 · about 2.5 hours
Job control
You end with a shell where sleep 100 & runs in the background, Ctrl-Z pauses a program, fg and bg bring it back, and Ctrl-C stops only the program, never the shell.
Step 4.1: Why Ctrl-C does not kill the shell (about 30 minutes)
When you press Ctrl-C, the terminal does not know about your shell or sleep. It sends SIGINT, a signal (a small message the kernel delivers to a process), to every process in one process group, the foreground group of that terminal. A process group is a set of processes that are signalled together, and a pipeline like a | b | c forms one so that Ctrl-C stops all three.
That gives the design:
- The shell puts itself in its own group and makes it the foreground group, so it owns the terminal while you type at the prompt.
- It ignores
SIGINT,SIGQUITandSIGTSTP(Ctrl-Z) itself, so keystrokes meant for programs cannot touch it. - For each job, it creates a new group, hands the terminal to it (
tcsetpgrp), waits, and then takes the terminal back.
The setup runs once at start-up, and only if standard input is a terminal:
/// Turn the shell into a job-control shell, if a person is typing at a terminal.
pub fn init(shell: &mut Shell) {
unsafe {
if libc::isatty(0) == 0 {
return;
}
// The shell must survive Ctrl-C, Ctrl-Z and terminal handoffs that are meant for the jobs it runs.
for sig in [libc::SIGINT, libc::SIGQUIT, libc::SIGTSTP, libc::SIGTTIN, libc::SIGTTOU] {
libc::signal(sig, libc::SIG_IGN);
}
// Take a process group of our own, and make it the one the terminal sends keystrokes to.
let pid = libc::getpid();
libc::setpgid(pid, pid);
libc::tcsetpgrp(0, pid);
shell.shell_pgid = pid;
shell.interactive = true;
}
}
When a script or a pipe feeds the shell, init does nothing, and none of the group handling runs. Scripts do not need it.
Step 4.2: Give each job a group, and the terminal (about 45 minutes)
Each job also needs a record. A Job remembers its processes, its group, a label for jobs to print, and whether it is running or stopped:
pub enum State {
Running,
Stopped,
}
/// One pipeline that is running, or paused, in the background or the foreground.
pub struct Job {
pub id: usize,
pub pgid: i32, // the process group all its processes share (when job control is on)
pub pids: Vec<i32>,
pub status: Vec<Option<i32>>, // exit status per process, None while it is still alive
pub text: String,
pub state: State,
}
In the child, right after fork, a few lines set the group and the terminal and then undo the shell's signal settings, so that a program behaves normally:
/// What a child needs to know about where it sits in the job.
struct Placement {
stdin_fd: Option<i32>,
stdout_fd: Option<i32>,
pgid: Option<i32>, // Some(0): lead a new process group. Some(n): join group n. None: no job control.
foreground: bool, // should this group own the terminal?
no_stdin: bool, // a background job in a script must not read the script's input
}
/// Everything the child does between fork and exit. Never returns.
unsafe fn child_main(shell: &mut Shell, cmd: &Command<String>, place: &Placement, all_pipe_fds: &[i32]) -> ! {
if let Some(pgid) = place.pgid {
libc::setpgid(0, pgid);
if place.foreground {
libc::tcsetpgrp(0, libc::getpgrp()); // signals are still ignored here, so this cannot stop us
}
}
// The shell ignores these so that Ctrl-C and Ctrl-Z only hit the jobs. Jobs must get the normal behaviour back.
// Rust also ignores SIGPIPE in its own programs, and programs we exec inherit that. Put it back too.
for sig in [libc::SIGINT, libc::SIGQUIT, libc::SIGTSTP, libc::SIGTTIN, libc::SIGTTOU, libc::SIGPIPE] {
libc::signal(sig, libc::SIG_DFL);
}
if place.no_stdin && place.stdin_fd.is_none() {
let null = cstring("/dev/null");
let fd = libc::open(null.as_ptr(), libc::O_RDONLY);
libc::dup2(fd, 0);
libc::close(fd);
}
let (stdin_fd, stdout_fd) = (place.stdin_fd, place.stdout_fd);
if let Some(fd) = stdin_fd {
libc::dup2(fd, 0);
}
if let Some(fd) = stdout_fd {
libc::dup2(fd, 1);
}
for &fd in all_pipe_fds {
libc::close(fd); // the copies we duped are enough; leftovers would keep pipes open forever
}
if let Err(msg) = apply_redirs(&cmd.redirs) {
eprintln!("rsh: {msg}");
libc::_exit(1);
}
if is_builtin(&cmd.argv[0]) {
let status = run_builtin(shell, &cmd.argv);
std::io::stdout().flush().ok();
libc::_exit(status);
}
let args: Vec<CString> = cmd.argv.iter().map(|a| cstring(a)).collect();
let mut ptrs: Vec<*const libc::c_char> = args.iter().map(|a| a.as_ptr()).collect();
ptrs.push(std::ptr::null());
libc::execvp(ptrs[0], ptrs.as_ptr());
// execvp only returns when it failed.
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::NotFound {
eprintln!("rsh: {}: command not found", cmd.argv[0]);
libc::_exit(127);
}
eprintln!("rsh: {}: {err}", cmd.argv[0]);
libc::_exit(126);
}
The first child of a pipeline leads a new group (setpgid(0, 0)), and the others join it. Look at the parent after fork in run_pipeline: it calls setpgid for the child too. That is deliberate. After a fork we cannot know whether parent or child runs first, and the group must exist before anyone uses it, so both sides make the same call and whichever runs first wins. The second call is harmless.
The waiting side gives the terminal to the group, waits, and takes it back:
/// Give the job the terminal, wait for it, then take the terminal back.
pub fn foreground(shell: &mut Shell, index: usize) -> i32 {
let pgid = shell.jobs[index].pgid;
if shell.interactive {
unsafe { libc::tcsetpgrp(0, pgid) };
}
if shell.jobs[index].state == State::Stopped {
unsafe { libc::kill(-pgid, libc::SIGCONT) };
shell.jobs[index].state = State::Running;
}
let outcome = wait_job(shell, index);
if shell.interactive {
unsafe { libc::tcsetpgrp(0, shell.shell_pgid) };
}
match outcome {
Outcome::Finished(status) => {
shell.jobs.remove(index);
renumber_if_empty(shell);
if status == 128 + libc::SIGINT {
println!(); // the terminal echoed ^C but not the newline
}
status
}
Outcome::Stopped => {
assign_id(shell, index); // a job gets a number once it is paused, like one sent to the background
println!();
announce(shell, index, "Stopped");
128 + libc::SIGTSTP
}
}
}
Step 4.3: Background jobs and reaping (about 40 minutes)
A trailing & means: start the job, do not wait. The parser has a new field for that, and the executor skips the waiting. But now the shell has children it did not wait for, and a finished child that nobody collects stays around as a zombie, an entry in the process table that only exists to hold its exit status until someone asks for it. So before every prompt the shell makes a quick, non-blocking pass over its jobs:
Pitfall: a finished background job that nobody waits for stays in the process table as a zombie. If ps shows <defunct> entries under your shell, the pass over the jobs before the prompt is missing.
/// Pick up news about background jobs without waiting. Call this before each prompt.
pub fn reap(shell: &mut Shell) {
let mut i = 0;
while i < shell.jobs.len() {
let job = &mut shell.jobs[i];
for k in 0..job.pids.len() {
if job.status[k].is_some() {
continue;
}
let mut raw = 0;
let flags = libc::WNOHANG | libc::WUNTRACED | libc::WCONTINUED;
let got = unsafe { libc::waitpid(job.pids[k], &mut raw, flags) };
if got == job.pids[k] {
if libc::WIFSTOPPED(raw) {
job.state = State::Stopped;
} else if libc::WIFCONTINUED(raw) {
job.state = State::Running;
} else {
job.status[k] = Some(decode_status(raw));
}
} else if got < 0 {
job.status[k] = Some(1);
}
}
if shell.jobs[i].status.iter().all(|s| s.is_some()) {
if shell.interactive {
announce(shell, i, "Done");
}
shell.jobs.remove(i);
renumber_if_empty(shell);
} else {
i += 1;
}
}
}
WNOHANG makes waitpid return immediately when there is nothing to report, so the prompt never freezes. When a job has fully finished, an interactive shell prints [1]+ Done, and the job leaves the table.
One more thing is easy to miss. A background job in a script must not read from the script's own input, or cat & would swallow the following lines of the file. The child therefore reads from /dev/null in that case (the no_stdin field above). Try it:
sh -c 'sleep 1; echo slow one done' &
echo "started it, not waiting"
jobs
wait
echo "after wait"
cat &
echo "cat did not eat the script"
wait
sleep 0.2 & sleep 0.2 & wait; echo "two jobs finished"
started it, not waiting
[1]+ Running sh -c sleep 1; echo slow one done
slow one done
after wait
cat did not eat the script
two jobs finished
sh -c '...' & returned at once and the next line ran immediately, then jobs showed it running, and wait held until it finished. The cat & did not eat the script.
Step 4.4: Stop, fg and bg (about 35 minutes)
Ctrl-Z sends SIGTSTP, which pauses the foreground group. The shell notices because waitpid was called with the WUNTRACED flag: without it, a stopped child is invisible. The shell marks the job as stopped, prints it, and returns to the prompt. This is where a job gets its number, which is why sleep 5 alone never shows up as [1].
Pitfall: without the WUNTRACED flag, waitpid never reports a stopped child, so the shell does not notice that the job stopped.
To resume it, fg gives the terminal back to the job's group and sends SIGCONT (continue) to the whole group. bg sends the same signal without taking the terminal, so the job runs in the background.
To test this we need a real terminal, because the keyboard signals come from the terminal driver. Python's pty module creates a pseudo-terminal, a fake terminal that a program can type into, and we run the shell inside it:
import os
import pty
import re
import select
import signal
import time
def read_available(fd, wait=0.6):
"""Collect what the terminal shows until it goes quiet."""
out = b""
while select.select([fd], [], [], wait)[0]:
try:
chunk = os.read(fd, 4096)
except OSError:
break
if not chunk:
break
out += chunk
return out.decode(errors="replace").replace("\r\n", "\n")
pid, fd = pty.fork()
if pid == 0:
os.execv("./target/release/rsh", ["rsh"])
shown = read_available(fd)
transcript = [shown]
def type_keys(keys, wait=0.6):
os.write(fd, keys.encode())
transcript.append(read_available(fd, wait))
type_keys("sleep 30\n", 0.3) # starts in the foreground and holds the terminal
type_keys("\x1a") # Ctrl-Z
type_keys("jobs\n")
type_keys("bg\n")
type_keys("jobs\n")
type_keys("fg\n", 0.3)
type_keys("\x03") # Ctrl-C reaches the job, not the shell
type_keys("echo shell is still here $?\n")
type_keys("sleep 0.3 &\n")
time.sleep(0.6)
type_keys("echo next prompt\n")
type_keys("exit\n")
text = "".join(transcript)
text = re.sub(r"\[(\d+)\] \d+", r"[\1] <pid>", text)
print(text.strip())
rsh$ sleep 30
^Z
[1]+ Stopped sleep 30
rsh$ jobs
[1]+ Stopped sleep 30
rsh$ bg
[1]+ sleep 30 &
rsh$ jobs
[1]+ Running sleep 30
rsh$ fg
sleep 30
^C
rsh$ echo shell is still here $?
shell is still here 130
rsh$ sleep 0.3 &
[1] <pid>
rsh$ echo next prompt
next prompt
[1]+ Done sleep 0.3
rsh$ exit
Read the transcript from the top. ^Z stopped sleep 30, and jobs listed it as stopped. bg resumed it in the background and jobs showed it running. fg brought it forward, and ^C ended it with status 130, which is 128 plus the signal number 2. The shell itself kept running, and the following echo proves it. The last job, sleep 0.3 &, finished in the background, and the shell announced Done at the next prompt.
Pid numbers vary from run to run, so the test replaces them with <pid>.
Phase 4 done
You wrote the part of a shell that most people never see: process groups, who owns the terminal, which signals go where, and how a parent finds out what its children did.