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.

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
fn main() {
for i in 0..1_000_000 {
println!("{i}");
}
}cargo run -q | head -n 10
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
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:
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
| Program | Choice |
|---|---|
| Filter that streams lines | Fix 2, or Fix 1 if you use a buffered writer anyway |
| Tool with cleanup on exit | Fix 1, so destructors and flushes run |
| Server or long-running process | Keep 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.


