Errno::EPIPE
RubyWARNINGCriticalIO
Broken pipe — reader has closed
Quick Answer
Rescue Errno::EPIPE around writes to pipes and sockets; exit gracefully when the reader is gone.
What this means
Raised when a process tries to write to a pipe or socket whose reading end has been closed. Common when piping Ruby output to tools like head or less that close stdin before all data is consumed. Maps to POSIX errno 32.
Why it happens
- 1Writing to $stdout when piped output is closed early (e.g., ruby script.rb | head -5)
- 2Writing to a socket after the remote end has closed the connection
Fix
Rescue EPIPE in output loops
Rescue EPIPE in output loops
begin
items.each { |item| puts item }
rescue Errno::EPIPE
exit 0 # reader is done — exit cleanly
endWhy this works
Rescuing EPIPE and exiting with 0 mirrors the behaviour of standard Unix utilities like cat.
Code examples
Common occurrence with headruby
# ruby generate_lines.rb | head -1 # Errno::EPIPE on the 2nd write after head closes stdin
Suppress EPIPE for CLI toolsruby
Signal.trap('PIPE', 'SIG_DFL') # let OS handle SIGPIPE silentlyRescue in socket writeruby
begin socket.write(data) rescue Errno::EPIPE socket.close end
Same error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev