Ray's Knowledge Base
Unlock

println! panics on a closed pipe in a Rust CLI; route stdout through one BrokenPipe-aware helper

PitfallVerified 17 Oct 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

A CLI that streams to stdout, piped into a reader that closes early (rmaestro events --follow | head -c 30), exits 101 with a panic message instead of exiting cleanly.

Cause#

println! panics when the write to stdout fails. A closed pipe makes the write fail with ErrorKind::BrokenPipe.

Fix#

Send every stdout write through one helper that uses writeln!(std::io::stdout().lock(), ..). Map ErrorKind::BrokenPipe to a dedicated Error::Pipe whose exit code is 0 and which prints nothing. Add a test that closes the reader after the first line and asserts exit status 0 and no panicked on stderr.

Evidence#

Audit finding on the rmaestro CLI (TSK-m7p2gn). The fix was output::line plus the test cli_closed_pipe_exits_clean. A manual events --follow | head -c 30 then printed the first 30 header characters with empty stderr.