Skip to content
rusthacks.dev
Tooling

Rust Error Broken Pipe When Writing to Standard Output

Piping your Rust program into head makes println panic with Broken pipe. Rust ignores SIGPIPE, so handle the write error, or restore the default signal behavior in tools.

2 min read
Summarize in AI
Flat illustration for the post “Rust Error Broken Pipe When Writing to Standard Output”, composed around cli.

You wrote a nice Unix-style filter, piped it into head and got a panic message. The program did nothing wrong: head read what it needed, closed its end and left, and the next write found nobody there. C programs would be killed by a signal and nobody would notice. Rust turns the signal off and hands you an error, which println! converts to a panic. This post shows three fixes. It belongs with reading standard input and exit codes, and sits in the debugging cluster next to address already in use.

Rust 1.90, Unix.

Reproduce

rust
fn main() {
    for i in 0..1_000_000 {
        println!("{i}");
    }
}
Shell
cargo run -q | head -n 1
Text
0
thread 'main' panicked at library/std/src/io/stdio.rs:1165:9:
failed printing to stdout: Broken pipe (os error 32)

head printed 0, exited, and the next println! failed. The exact path in the panic message depends on the Rust version.

Fix 1: handle the error

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

fn main() -> io::Result<()> {
    let stdout = io::stdout().lock();
    let mut out = BufWriter::new(stdout);
    for i in 0..1_000_000 {
        if let Err(e) = writeln!(out, "{i}") {
            if e.kind() == ErrorKind::BrokenPipe {
                return Ok(());
            }
            return Err(e);
        }
    }
    out.flush().or_else(|e| if e.kind() == ErrorKind::BrokenPipe { Ok(()) } else { Err(e) })
}

The program exits normally with status 0 when the reader leaves. The flush also can fail with BrokenPipe, so it is checked too. Locking stdout once and buffering makes the output much faster than println!, which locks and flushes per line when stdout is a terminal.

Fix 2: restore the default signal

For command line filters that should behave like Unix tools:

rust
fn main() {
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
    for i in 0..1_000_000 {
        println!("{i}");
    }
}

The process is killed by SIGPIPE on the first write to a closed pipe, silently, as in C. The shell reports exit status 141. The call is unsafe and needs the libc crate. Do it at the top of main in tools only. In a server it would make a closed client socket kill the process.

Fix 3: stop reading earlier

If the broken pipe appears in a tool that wraps another command, check whether your own loop can stop when the output is no longer needed. A write error is the only signal you receive.

Which to choose

ProgramChoice
Filter that streams linesFix 2, or Fix 1 if you use a buffered writer anyway
Tool with cleanup on exitFix 1, so destructors and flushes run
Server or long-running processKeep the signal ignored, handle errors per connection

Limits

eprintln! also panics if stderr is closed. Windows has no SIGPIPE, and a closed pipe yields ErrorKind::BrokenPipe or an ERROR_NO_DATA message instead. The behavior is documented in the standard library for the BrokenPipe error kind.

Also inCLI
Taggedsigpipe
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.