knaxuslearn · build · ship

Projects / Unix shell / Phase 2

Phase 2 of 4 · about 2.5 hours

Pipes and redirects

You end with a shell that runs a | b | c, sends output to files and reads input from them, and does it by calling fork, pipe, dup2 and exec yourself.

Step 2.1: From words to a structure (about 35 minutes)

ls | wc -l > count.txt has structure: two commands, a pipe between them, and a redirect on the second. We cannot find that structure in a list of strings, so the lexer now produces tokens, which are either words or operators:

/// One piece of a command line.
#[derive(Debug, Clone, PartialEq)]
pub enum Token {
    Word(String),
    Pipe,      // |
    In,        // <
    Out,       // >
    Append,    // >>
    ErrOut,    // 2>
    ErrToOut,  // 2>&1
    Semi,      // ;
    And,       // &&
    Or,        // ||
    Amp,       // &
}

The scanner gets one new arm for each operator (the excerpt starts at the backslash arm, just above them). Quotes keep working, because the quote arms consume everything up to the closing quote before an operator character is ever looked at, so "a|b" stays one word.

            '\\' => {
                in_word = true;
                match chars.next() {
                    Some(ch) => word.push(ch),
                    None => return Err("line ends with a backslash".into()),
                }
            }
            '|' => {
                flush!();
                if chars.peek() == Some(&'|') {
                    chars.next();
                    tokens.push(Token::Or);
                } else {
                    tokens.push(Token::Pipe);
                }
            }
            '&' => {
                flush!();
                if chars.peek() == Some(&'&') {
                    chars.next();
                    tokens.push(Token::And);
                } else {
                    tokens.push(Token::Amp);
                }
            }
            ';' => {
                flush!();
                tokens.push(Token::Semi);
            }
            '<' => {
                flush!();
                tokens.push(Token::In);
            }
            '>' => {
                flush!();
                if chars.peek() == Some(&'>') {
                    chars.next();
                    tokens.push(Token::Append);
                } else {
                    tokens.push(Token::Out);
                }
            }
            // "2>" and "2>&1" only mean something at the start of a word: in "file2>x" the 2 is part of the name.
            '2' if !in_word && chars.peek() == Some(&'>') => {
                chars.next();
                let mut rest = chars.clone();
                if rest.next() == Some('&') && rest.next() == Some('1') {
                    chars.next();
                    chars.next();
                    tokens.push(Token::ErrToOut);
                } else {
                    tokens.push(Token::ErrOut);
                }
            }

Two details worth a second look. A | followed by another | is ||, and a > followed by another > is >>. And 2> is only special at the very start of a word, so in ls file2>x the 2 stays part of the file name, just like in a real shell.

Next, a parser turns the tokens into a structure the executor can follow:

#[derive(Debug, Clone, PartialEq)]
pub enum Redir {
    In(String),
    Out(String),
    Append(String),
    ErrOut(String),
    ErrToOut,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct Command {
    pub argv: Vec<String>,
    pub redirs: Vec<Redir>,
}

/// Commands joined by `|`. The output of each one feeds the input of the next.
pub type Pipeline = Vec<Command>;
/// Parse tokens into one pipeline. An empty line gives an empty pipeline.
pub fn parse_pipeline(tokens: &[Token]) -> Result<Pipeline, String> {
    if tokens.is_empty() {
        return Ok(Vec::new());
    }
    let mut pipeline = Vec::new();
    let mut cmd = Command::default();
    let mut iter = tokens.iter();

    while let Some(tok) = iter.next() {
        match tok {
            Token::Word(w) => cmd.argv.push(w.clone()),
            Token::In => cmd.redirs.push(Redir::In(file_after(&mut iter, "<")?)),
            Token::Out => cmd.redirs.push(Redir::Out(file_after(&mut iter, ">")?)),
            Token::Append => cmd.redirs.push(Redir::Append(file_after(&mut iter, ">>")?)),
            Token::ErrOut => cmd.redirs.push(Redir::ErrOut(file_after(&mut iter, "2>")?)),
            Token::ErrToOut => cmd.redirs.push(Redir::ErrToOut),
            Token::Pipe => {
                if cmd.argv.is_empty() {
                    return Err("syntax error near |".into());
                }
                pipeline.push(std::mem::take(&mut cmd));
            }
            Token::Semi | Token::And | Token::Or | Token::Amp => {
                return Err("; && || and & are not supported yet".into());
            }
        }
    }
    if cmd.argv.is_empty() {
        return Err("syntax error: a command is missing".into());
    }
    pipeline.push(cmd);
    Ok(pipeline)
}

A Command is the program and its arguments plus its redirects. A Pipeline is a list of commands. The parser walks the tokens once. A word joins the current command, a redirect operator takes the next word as its file name, and a | closes the current command and starts the next. It refuses a | with nothing before it, and a redirect with no file name.

running 10 tests
..........
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Step 2.2: fork and exec by hand (about 40 minutes)

Unix starts programs with two separate calls, and that split is the whole trick behind pipes and redirects.

  • fork makes a copy of the current process. Afterwards there are two, almost identical. In the copy (the child) fork returns 0, and in the original (the parent) it returns the child's process id.
  • exec replaces the running program inside a process with a different program. The process id and the open files stay the same.

Between the two calls, the child is still our code, so it can rearrange its own file descriptors before the new program starts. A file descriptor is the small number that names an open file: 0 is the standard input, 1 the standard output and 2 the standard error. The new program just reads 0 and writes 1, and has no idea where they lead. This is why we cannot keep using std::process::Command for the rest of the project: it does not let us do our own work in that gap.

These calls are raw system calls from the libc crate, so Rust makes us mark them unsafe. That does not mean they are dangerous. It means the compiler cannot check them, and we promise to use them correctly. Here is what the child does:

/// Everything the child does between fork and exit. Never returns.
unsafe fn child_main(cmd: &Command, stdin_fd: Option<i32>, stdout_fd: Option<i32>, all_pipe_fds: &[i32]) -> ! {
    // Rust ignores SIGPIPE in its own programs, and programs we exec inherit that. Put it back.
    libc::signal(libc::SIGPIPE, libc::SIG_DFL);

    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(&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);
}
  • If a command is a built-in inside a pipeline (pwd | cat), the child runs it and leaves with _exit. _exit skips Rust's normal cleanup, which belongs to the parent's copy of the program.
  • execvp searches $PATH for the program and replaces the child with it. If it returns at all, it failed, so the lines after it report the error. A missing program gives 127, and anything else gives 126.
  • The SIGPIPE line fixes a quiet trap that belongs to Rust. Rust programs ignore that signal, and a program started with exec inherits the ignoring. Without the line, yes | head -n 1 would never stop, because yes would get an error from every write and keep going. We restore the default, which is to die when the reader goes away.

Step 2.3: Pipes (about 45 minutes)

A pipe is a one-way channel with two ends, each a file descriptor. Bytes written into the write end come out of the read end. For a | b | c we need two pipes. Command a writes into the first, b reads from the first and writes into the second, and c reads from the second.

/// Run a pipeline and wait for it. Returns the exit status of the last command.
pub fn run_pipeline(pipeline: &Pipeline) -> i32 {
    // A lone built-in with no redirects runs inside the shell itself, so `cd` can change our directory.
    if pipeline.len() == 1 && pipeline[0].redirs.is_empty() && is_builtin(&pipeline[0].argv[0]) {
        return run_builtin(&pipeline[0].argv);
    }

    let n = pipeline.len();
    let mut pipes: Vec<[i32; 2]> = Vec::new();
    for _ in 1..n {
        let mut fds = [0; 2];
        if unsafe { libc::pipe(fds.as_mut_ptr()) } < 0 {
            eprintln!("rsh: pipe: {}", std::io::Error::last_os_error());
            return 1;
        }
        pipes.push(fds);
    }
    let all_pipe_fds: Vec<i32> = pipes.iter().flat_map(|p| p.iter().copied()).collect();

    let mut pids = Vec::new();
    for (i, cmd) in pipeline.iter().enumerate() {
        let stdin_fd = if i > 0 { Some(pipes[i - 1][0]) } else { None };
        let stdout_fd = if i + 1 < n { Some(pipes[i][1]) } else { None };
        std::io::stdout().flush().ok(); // do not let the child inherit text we have not written yet
        match unsafe { libc::fork() } {
            -1 => eprintln!("rsh: fork: {}", std::io::Error::last_os_error()),
            0 => unsafe { child_main(cmd, stdin_fd, stdout_fd, &all_pipe_fds) },
            pid => pids.push(pid),
        }
    }

    // The shell must close its copies, or the last reader never sees end-of-file.
    for fd in all_pipe_fds {
        unsafe { libc::close(fd) };
    }

    let mut status = 1;
    for (i, pid) in pids.iter().enumerate() {
        let mut raw = 0;
        unsafe { libc::waitpid(*pid, &mut raw, 0) };
        if i + 1 == pids.len() {
            status = decode_status(raw);
        }
    }
    status
}

Follow what happens:

  1. We create all the pipes first, then fork one child per command.
  2. Each child uses dup2(fd, 0) and dup2(fd, 1) to make its pipe ends become its standard input and output. dup2(old, new) makes descriptor new point to whatever old points to.
  3. Then every child closes every pipe descriptor, and so does the parent. This is the step people forget, and it matters: a reader only sees end-of-file when all the write ends are closed. If one stray copy stays open anywhere, wc waits for input forever and the whole pipeline hangs.
  4. The parent waits for every child and reports the status of the last one. That is also what bash does: the status of false | true is 0.

A lone built-in with no redirects runs inside the shell itself, which is what keeps cd working. cd dir | cat forks like any other pipeline, so the cd only affects a throwaway child, and the shell's directory stays where it was.

Pipes also show why status values need decoding. waitpid gives a packed number, and the macros WIFEXITED, WEXITSTATUS, WIFSIGNALED and WTERMSIG take it apart. A program killed by signal 13 (SIGPIPE) shows up as 128 + 13, which is how every shell reports it.

Step 2.4: Redirects (about 30 minutes)

A redirect is another use of the gap between fork and exec. To send standard output to a file, the child opens the file and uses dup2 to make it descriptor 1:

unsafe fn redirect_to_file(path: &str, flags: i32, target: i32) -> Result<(), String> {
    let c_path = cstring(path);
    let fd = libc::open(c_path.as_ptr(), flags, 0o644);
    if fd < 0 {
        return Err(format!("{path}: {}", std::io::Error::last_os_error()));
    }
    libc::dup2(fd, target);
    libc::close(fd);
    Ok(())
}

/// Apply a command's redirects, in the order they were written.
unsafe fn apply_redirs(redirs: &[Redir]) -> Result<(), String> {
    for r in redirs {
        match r {
            Redir::In(path) => redirect_to_file(path, libc::O_RDONLY, 0)?,
            Redir::Out(path) => redirect_to_file(path, libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC, 1)?,
            Redir::Append(path) => redirect_to_file(path, libc::O_WRONLY | libc::O_CREAT | libc::O_APPEND, 1)?,
            Redir::ErrOut(path) => redirect_to_file(path, libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC, 2)?,
            Redir::ErrToOut => {
                libc::dup2(1, 2);
            }
        }
    }
    Ok(())
}

The loop applies redirects in the order they were written, and the order matters. 2>&1 means "make descriptor 2 point to wherever 1 points right now", so it depends on what 1 is at that moment. Try both orders and count the lines that travel through the pipe:

ls /nonexistent 2>&1 >/dev/null | wc -l
ls /nonexistent >/dev/null 2>&1 | wc -l
1
0

In the first line, stderr is copied to the pipe first, and only then does stdout go to /dev/null, so the error message goes through the pipe and wc counts 1. In the second line, stdout goes to /dev/null first, so stderr is copied there too, and nothing is left for the pipe.

Now the whole phase together:

echo hello world
echo "two  spaces" | tr a-z A-Z
printf 'b\na\nc\n' | sort | head -n 2
echo first > out.txt
echo second >> out.txt
cat < out.txt
ls /nonexistent 2> err.txt
cat err.txt
ls /nonexistent 2>&1 | wc -l
nosuchcmd
cd /usr
pwd
yes | head -n 2
echo "a | b" | tr a-z A-Z
hello world
TWO  SPACES
a
b
first
second
ls: cannot access '/nonexistent': No such file or directory
1
rsh: nosuchcmd: command not found
/usr
y
y
A | B

Check each line against what you expect. The pipeline sorts and trims, > overwrites while >> appends, < reads a file, the error went to err.txt and not the screen, and yes | head -n 2 finished instead of hanging.

Phase 2 done

You now run pipelines by hand with fork, pipe, dup2 and exec, and you know why each descriptor is closed where it is. The shell still treats every line as one pipeline. Phase 3 makes it a language.