Articles / Rust

  • rust
  • cli
  • sigpipe
  • pipes
  • error-handling
  • debugging

Why a Rust CLI Panics When You Pipe It into head

Your Rust program prints a list perfectly well. Then someone pipes it into head, about the most ordinary thing you can do to a command line tool, and it panics over a closed pipe.

fn main() {
    for i in 0..100_000 {
        println!("line {i}");
    }
}

Here it is with Rust 1.100.0 on Linux (thread ID and source path trimmed):

$ ./a | head -n 1
line 0

thread 'main' panicked at library/std/src/io/stdio.rs:
failed printing to stdout: Broken pipe (os error 32)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
$ echo ${PIPESTATUS[*]}
101 0

head leaves, and the next write has nowhere to go

head -n 1 reads what it needs, prints one line and exits, which closes the read end of the pipe. Your program is still looping, and its next write to a pipe with no readers cannot succeed.

Unix normally handles this by sending the writer a signal, SIGPIPE, whose default action is to kill the process without printing anything. It is how yes | head ever finishes.

The Rust runtime sets SIGPIPE to ignored before your main runs. With the signal ignored, the kernel instead makes write fail with EPIPE, which is error 32. Rust turns that into an ordinary io::Error of kind BrokenPipe.

For a network server this is sensible, because one client hanging up should not kill the whole process. For a filter in a shell pipeline, it is the opposite of what you wanted.

println! has no way to hand you the error

println! returns (). When the write fails, it can either drop the error or panic, and its documentation says it panics. So the chain is short:

  1. head exits and closes the pipe.
  2. SIGPIPE is ignored, so write returns an error.
  3. println! cannot return it, so it panics.
  4. The panic on the main thread exits with status 101.

If you build with panic = "abort", step four becomes an abort instead, and the shell reports 134. A very dramatic way to say "you only wanted one line".

It only fails if you are still writing

Quick detour, because this is why the bug survives testing. A pipe has a buffer in the kernel. A program with a little output can put all of it there and finish before the reader has gone anywhere, so no write ever fails.

Whether you see the panic depends on how much you print and who gets scheduled first. Test with plenty of output, such as the 100,000 lines above. The three rows in your fixture file may never trigger it.

Fix one: write with writeln! and handle BrokenPipe

The portable fix is to use writeln!, which returns a Result, and decide at the top of the program what a broken pipe means.

use std::io::{self, BufWriter, ErrorKind, Write};
use std::process::ExitCode;

fn run(out: &mut impl Write) -> io::Result<()> {
    for i in 0..100_000 {
        writeln!(out, "line {i}")?;
    }
    out.flush()
}

fn main() -> ExitCode {
    let mut out = BufWriter::new(io::stdout().lock());
    match run(&mut out) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) if e.kind() == ErrorKind::BrokenPipe => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}

Swapping the macro alone is not enough. If you add ? and let main return the error, the panic goes away but you get this, with exit status 1:

Error: Os { code: 32, kind: BrokenPipe, message: "Broken pipe" }

Three details in the longer version matter:

  • The explicit flush reports errors from the last buffered chunk. Dropping a BufWriter silently discards them.
  • Only BrokenPipe is forgiven. Run it with >/dev/full and you still get "No space left on device" and a failing status.
  • run only writes to stdout. If your real one also talks to a socket, don't let this match swallow that socket's broken pipe too.

Returning success is a choice. The reader got what it asked for, so I think it is the right one for most listing tools. If an unfinished run means unfinished work, say a migration that logs as it goes, a closed log pipe should not quietly count as success.

Fix two: give SIGPIPE its default action back

If your tool is purely a filter, you can restore the traditional Unix behaviour. This needs the libc crate (cargo add libc) and one unsafe call.

fn main() {
    // SAFETY: called first thing, before any other threads exist,
    // and SIG_DFL installs no Rust code as a handler.
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }

    for i in 0..100_000 {
        println!("line {i}");
    }
}

Now head gets its line and the writer dies quietly. Every println! can stay where it is, including those in dependencies.

The costs are real, though:

  • The process is killed on the spot, so destructors and cleanup code do not run.
  • The setting is process-wide. A pipe or socket write that does not suppress the signal itself can now kill you.
  • The shell reports status 141 (128 plus signal 13). Under set -o pipefail, that makes the pipeline fail.
  • It does nothing for Windows, where you still need to handle the error.

The standard library may already be doing this for your children

Hang on, if Rust ignores SIGPIPE, and ignored signals survive exec, do programs launched from Rust inherit that? By default, no. std::process::Command puts SIGPIPE back to default in the child, as the unstable book describes.

You can see it by comparing the SigIgn line in /proc/self/status. In my test the Rust parent showed 0000000000001000 (the SIGPIPE bit), while a grep it spawned showed all zeroes.

That same page documents a nightly-only compiler flag, -Zon-broken-pipe=kill, which sets the default action without your own unsafe block. It is unstable, and the tracking issue describes plans to replace it, so I would not build a release process around it.

Which one to use

I would handle the error by default. It keeps cleanup working, behaves predictably in scripts and does not change how the rest of the process treats signals. Restoring SIG_DFL is reasonable for a small, single-purpose Unix filter with nothing to tidy up.

Whichever you pick, add this to your checks. It needs Bash:

./target/release/yourtool | head -n 1
echo "${PIPESTATUS[0]}"

Expect 0 with the first fix and 141 with the second, given enough output to outlast the reader. If you see 101, there is still a println! on the path.