Broken pipe errno 32: SIGPIPE, EPIPE, and the Bytes a Reader Leaves

Dark cover headed 'Broken pipe': errno 32, SIGPIPE ignored by Python, a 65,536-byte buffer that a departing reader discards, and 34 passing tests

Updated December 3, 2026 · every figure below was measured on the host described in Section 1 unless its table marks it as documented, and a table that counts runs says how many it used.

A nightly report writes a line per account to standard output, and the operator reads it through head -n 20. Most mornings the job ends with a traceback: BrokenPipeError: [Errno 32] Broken pipe. Nothing is wrong with the report, the disk or the network. The reader asked for twenty lines and left, and the kernel tells the writer about it only when the writer next reaches a place the data cannot go. What makes this error harder than it looks is that the report is not wrong about the first twenty lines – they arrived – and the bytes that were already handed to the pipe after them are discarded when the reader closes.

The same number reaches a service in a different shape. A worker sending a response to a client that closed its tab gets EPIPE from send, or ECONNRESET (104) first and EPIPE second, depending on whether the peer’s close carried unread data. A shell sees the death of a producer as exit status 141 when pipefail is set, and a Python program sees exit status 120 with a note that the interpreter ignored an exception while shutting down. Behind all of it are two facts: the kernel counts a write as successful when a buffer accepted it, and the signal that would have killed the process (SIGPIPE) is ignored by CPython at startup.

TL;DR — EPIPE (32) is reported by the first write that finds no reader, and the exception carries no byte count. Two orders of events look the same and are worth telling apart: a write that reaches a pipe whose reader is already gone accepts nothing and fails on the spot, while a pipe that was full when the reader left had already taken a buffer – 65,536 bytes by default, 1,048,576 after the size was raised – and those bytes are discarded with the pipe. So a truncated head pipeline reports success while the last buffer it accepted is discarded. SIGPIPE (13) is the same condition as a signal; Python ignores it, so the call raises instead, and the process exits 1 with a traceback or 120 from the shutdown flush – not the 141 a shell tool reports. On a socket the first send to a closed peer can still succeed, which is why the error often arrives one call later than the disconnect.

Fix It First: Ten Changes, Matched to What You Saw

The first column is the evidence in front of you; the second is the cheapest check that separates this cause from the others; the third is the change that makes the evidence stop. Every row was produced by one of the matrices below, on the host described in Section 1.

What you seeCheapest checkChange that ends it
A cron job ends with BrokenPipeError and the output is completerun the same command with | cat and compare the exit statuscount the bytes the pipe accepted, treat a partial delivery as normal, and set sigpipe policy deliberately rather than inheriting it
Exit status 120 and one line beginning Exception ignored in:look for <_io.TextIOWrapper name='<stdout>'> in the messagethe shutdown flush failed: point the descriptor at devnull before exiting
The process died with signal 13 and printed no tracebackthe shell reports 141; kill -l 141 names SIGPIPEthis is the default disposition; either handle the error or accept the signal exit as the contract
The consumer received part of the stream and the producer logged successcompare the producer’s byte count with what the consumer wrotethe kernel accepted a buffer: count writes and stop on the first refusal
A server logs ECONNRESET, then EPIPE on the next writeread the errno of each write in order, not the last oneclassify the reset as the peer leaving, then stop writing to that connection
A client half-closed after its request and the server sent nothing backrecv returns empty while sends still succeeda FIN closes one direction: keep the response, send it, then close
send answers 9 (EBADF)check whether the descriptor was closed by this processthis is a local bug, not a broken pipe: fix the lifetime, do not retry
poll and select both call the pipe writable and the write still failsprint the poll event maskPOLLERR is set with POLLOUT: check the error bit before writing
shutdown(SHUT_WR) then any write answers EPIPEthe errno appears without a peer actionthis side closed its sending direction; open a new connection instead of retrying
One send after a peer’s close succeeds, the second failscount the sends after the disconnectthe first send was buffered and answered by a reset: never treat one success as proof the peer is reading
Table 1: Ten symptoms, the check that identifies each, and the change that ends it.

1. What the Number Measures, and on What Host

errno 32 is EPIPE, and its message on this host is “Broken pipe”. The number is not about a file, a path or a permission: it means a write reached a descriptor whose reading end no longer exists. Two different objects produce it – an anonymous pipe and a connected socket – and the kernel’s report is the same. What differs is what happened before the write, and that is where most of the diagnosis lives.

Every figure in this page was measured on the host below. A row that depends on timing or speed – a reader’s pace, a cost per call, a response writer racing a client – was run five times and prints its median and range; a row whose answer is an errno, an exit status or a poll mask was run once, because those do not move between runs. Values that come from another platform’s documentation are marked as documented and were not measured here; apart from the three documented rows of Table 13, every figure on this page was produced on this host.

ConditionValue on this host
Kernel6.12.118-guest-1.2
Python3.12.16, 64-bit
Machine and CPUsx86_64, 2 vCPU
Page size4,096 B
Shell/bin/dash as /bin/sh, with set -o pipefail accepted; /bin/bash 5.2.37 where a row names it
dash package versionnot readable in this image: dpkg-query -W dash answers “no packages found matching dash”, and dash --version answers Illegal option --, so this page claims only what the option does; a build without the patch stops at set: Illegal option -o pipefail, and Debian shipped the patch in dash 0.5.12-7 (documented)
Coreutilsls (GNU coreutils) 9.7
/tmptmpfs, page cache only
Pipescapacity 65,536 B default, 1,048,576 B maximum, atomic block 4,096 B
SocketsTCP over 127.0.0.1; the sequence table uses one-byte sends
Table 2: The host, the interpreter and the limits every figure in this page was measured under.

Two limits govern a pipe and they are often confused. Capacity is how much unread data the pipe can hold: the kernel reported 65,536 bytes for a default pipe and 1,048,576 bytes (1 MiB) after the size was raised, which is also the ceiling in /proc/sys/fs/pipe-max-size. The atomic block, PIPE_BUF, is how much a single write can add without interleaving with another writer: 4,096 bytes here. Neither number is a limit on how much a program may send; both matter only when a reader is slow or gone. A kernel counter that behaves the same way is symlink traversal, measured in the ELOOP runbook: a budget spent per step, not a size in bytes.

The third condition is the signal disposition, and it is not a property of the pipe at all. A process that writes to a pipe with no reader receives SIGPIPE and whatever its disposition says happens: the default terminates the process, a handler runs, and an ignored disposition turns the event into the errno. The next section measures the three dispositions rather than describing them.

2. SIGPIPE and EPIPE: One Condition, Two Policies

The kernel raises SIGPIPE for the writing thread and returns EPIPE from the call. Which of those a program experiences is decided by the disposition, and CPython changes the disposition before any program code runs. The measurement below takes the mask from the kernel itself, /proc/self/status, so it does not depend on what the process believes. Its 14 arms differ only in the program’s shape and its signal disposition.

A Python process shows SigIgn: 0000000001001000: bit 13 (SIGPIPE) and bit 25 (SIGXFSZ) are ignored. After the process asks for the default disposition with signal.signal, the mask becomes 0000000001000000 – the SIGPIPE bit is gone and only SIGXFSZ remains. /bin/dash on the same host, measured the same way, shows 0000000000000000: no signal ignored, so its children die on SIGPIPE. That single difference explains why seq and cat die quietly while a Python producer prints a traceback.

Shape of the programWhat the process did
os.write to a closed pipe, disposition ignored (the default)BrokenPipeError, exit 1
os.write to a closed pipe, disposition defaultkilled by signal 13, shell status 141
os.write of 4 KiB, disposition defaultkilled by signal 13
os.write of one byte, disposition defaultkilled by signal 13
print of 200,000 characters, bufferedexception inside print, exit 1
print of 1,000 characters, buffer held until exitexit 120
that print wrapped in try/except BrokenPipeErrorexit 120: the buffer still holds the bytes, so the shutdown flush raises again
the same print plus an explicit flush() inside the tryexit 120: the failed flush kept its bytes, and the shutdown flush retries them
catch, point stdout at devnull, exit 0 (the documented recipe)exit 0
catch, point stdout at devnull, exit 3exit 3
catch, call os._exit(1)exit 1
write after a failed flushexit 120, for the same reason
two writes after the reader leftexit 0, one errno line per write
signal.signal(SIGPIPE, SIG_DFL) from a threadValueError, main thread only
Table 3: Fourteen shapes of one write, the exit status each produced, and the one error that is not an exit status at all. Each was run once; an exit status does not move between runs.

The exit status is worth reading carefully because three different numbers appear for the same failure. A Python program that writes directly with os.write exits 1 and prints a traceback. A program whose only output is small enough to sit in the buffer until shutdown exits 120 and prints one line beginning Exception ignored in:; nothing in the program’s own code raised, because the flush that failed runs after it returned. That 120 is not a code the program chose: CPython uses it when a standard stream will not flush while the interpreter shuts down, and the flush fails because the bytes a failed flush left in the buffer are tried once more. A program killed by the signal – the disposition a C tool has by default – prints nothing at all and the shell reports 141. A supervisor that alerts on a non-zero exit treats all three the same, but a log pipeline that parses stderr sees only the first two.

There is a fourth ending, and the difference between it and the third is one line of code. Pointing the descriptor at devnull after catching the error gives exit 0 and no message, because the shutdown flush now writes to a file with no reader to lose. Calling os._exit instead skips the flush and gives exit 1, with no message either. The first keeps the program’s own exit code meaningful; the second abandons any cleanup that would have run after the write. Neither is a way to keep sending: the reader is gone, and the only question left is what the process tells its supervisor.

The disposition is a process-wide setting

A signal disposition belongs to the process, not to a thread, and Python enforces the rule: changing it from a worker thread raises ValueError and the process keeps running (exit 0, because the arm caught the error and returned). A service that wants death-on-SIGPIPE therefore has to set it in the main thread before the threads start, or run the writing work in a worker process. That is also why a library should not change the disposition as a side effect of being imported: it would change every other stream in the process, including the ones whose contract is an exception.

Why CPython ignores SIGPIPE in the first place

A write to a closed pipe would otherwise end the interpreter in the middle of a Python statement, with no chance to close files or report which line was running. Ignoring the signal turns the same condition into a Python exception that can be caught and attributed. The cost is that Python programs do not behave like shell tools by default, which is the mismatch behind most of the confusion in this page.

3. Pipe Capacity: What Is Accepted and What Is Discarded

In a truncated pipeline the producer is right about the bytes it handed over. write returns the number of bytes the kernel accepted into the pipe, and while a reader is attached the kernel accepts up to the pipe’s capacity whether or not that reader is keeping up. When the reader goes away the pipe goes with it: the bytes still in it are discarded, and the next write returns EPIPE. A write that arrives after the reader has already left is the simpler case – it accepts nothing, and fails on the spot. The exception carries no count either way, so a producer that only prints the error cannot say how much it delivered.

The table below runs the same writer with the same payload and changes one thing: how much the reader takes before it leaves. The writer asks for the pipe’s capacity first and writes fixed-size blocks; the reader takes its share, holds the pipe for 50 ms, and closes. The fourth column is accepted − read: plain arithmetic on the accepted count, not a second measurement. In a deliberate early stop such as head -n 20 that difference is exactly the work the consumer asked you not to do.

Reader’s behaviourPipe capacityBytes acceptedBytes discardedWhat it shows
Reader gone before the writer starts65,536 B0 B0 Bnothing is accepted once the reader is gone
Reader takes nothing, holds 50 ms, closes65,536 B65,536 B65,536 Ba whole buffer accepted and discarded
Reader takes one byte65,536 B65,536 B65,535 Ba 1-byte read leaves 4,095 B in that page slot, so no slot is free for the writer
Reader takes one 64 KiB block65,536 B131,072 B65,536 Bone buffer delivered, one buffer discarded
Reader takes two 64 KiB blocks65,536 B196,608 B65,536 Bthe discarded count stays one buffer
One-byte writes, reader takes one byte65,536 B65,536 B65,535 Bblock size does not change the bound
4 KiB writes, reader takes one byte65,536 B65,536 B65,535 Bsame bound, fewer calls
One-byte writes, 1 MiB pipe, reader takes one byte1,048,576 B111,615 (99,187–124,877) B111,614 (99,186–124,876) Bbounded by how fast the writer runs, not by capacity
4 KiB writes, 1 MiB pipe, reader takes one byte1,048,576 B1,048,576 B1,048,575 Bthe capacity is reached before the reader leaves
One 1 MiB write into a 1 MiB pipe1,048,576 B1,048,576 B1,048,575 Bone call, one buffer, one discard
Reader takes nothing, 1 MiB pipe1,048,576 B1,048,576 B1,048,576 Ba larger buffer holds more to discard
Table 4: Eleven ways a reader can leave, the bytes the kernel accepted before EPIPE, and the bytes the reader did not take.

Two rows need a word of explanation because they look inconsistent. With one-byte writes into the 1 MiB pipe the discarded count was 111,614 (99,186–124,876) bytes, not the full capacity: the writer simply could not fill a mebibyte one byte at a time within the 50 ms the reader stayed. That is a producer-speed bound, and it is the reason the row prints a range rather than one number. With 4 KiB writes at the same capacity the writer reached 1,048,576 bytes, and 1,048,575 were discarded – the capacity minus the one byte the reader took. A pipeline discards a buffer because the buffer was full when the reader left, not because a particular write was large.

The one-byte row is an accounting result, not a rounding error. A pipe holds its data in page-sized slots – 4,096 bytes here – and a read takes bytes from the head slot without handing that slot back: after a one-byte read the remaining 4,095 bytes still occupy it, the write end has no free slot to fill, and the next block is refused. The row that reads a whole block shows the other side of the same rule – a 64 KiB block is sixteen of those page slots, and reading all of it returns all sixteen, which is exactly the room one more 64 KiB block needs. Room in a pipe is counted in slots of a page, not in bytes read.

The practical consequence for head is exact, and it is not a defect in head. A producer that writes 64 KiB blocks and a consumer that runs head -n 20 will usually have one block in the pipe when head exits; if the consumer read a little more, one more block will have been accepted. The file the consumer writes is correct as far as it goes, because stopping early is what it was asked to do. What would be wrong is taking a partial delivery for a complete one: the producer’s exit status and its accepted count are the only places the difference appears, and only if someone asked for them – which is what pipefail does, in Section 6. When the reader is alive but slow rather than gone, the same full buffer produces EAGAIN instead; the EAGAIN runbook measures that side of the boundary.

Is the data in the pipe delivered after the reader closes?

No. Closing the last read descriptor discards whatever the pipe still held; a reader that closes has no way to drain it afterwards. That is why Table 4 counts these bytes as discarded rather than sent: the kernel accepted them from the writer, and the reader never saw them. The same is true of a socket’s send buffer once a reset is processed.

4. Python’s Three Surfaces: Call, Buffer, Shutdown

A Python program can meet EPIPE at three different layers, and the layer decides which exception it sees and whether the process survives. The raw call raises BrokenPipeError at the line that made it. A buffered stream accepts the write, returns its length, and raises at the next flush – which may be inside a later write that fills the buffer, or during interpreter shutdown after the program has finished. The shutdown case is the one that produces the confusing Exception ignored in: line.

SurfaceWhat it returned on this host
buffered.write(b"x" * 1000)returns 1,000; nothing reaches the pipe yet
buffered.flush() on a dead readerBrokenPipeError, errno 32
another write after the failed flushtaken into the buffer: accepted, on top of the 1,000 bytes still there
a second flush() of that buffer, against a raw writer that refuses once and then acceptsdelivered 1,001 bytes: the first 1,000 were never dropped
flush() and close() again on the real pipeBrokenPipeError and BrokenPipeError: both retry the same bytes
TextIOWrapper.write then flushwrite returns 1,000, flush raises the same errno
os.write(fd, b"") with no readerreturns 0 and raises nothing: there is nothing to deliver
select and poll on a pipe whose reader leftpoll 12 (POLLOUT|POLLERR); select names the descriptor writable and the write fails
os.write to a descriptor this process closederrno 9 (EBADF), not EPIPE
one hundred writes after the first EPIPEall 32: the socket or pipe stays broken
send after this side’s shutdown(SHUT_WR)errno 32 on both, not 108: the kernel reports a local shutdown as EPIPE
sendall to a closed peerBrokenPipeError, errno 32
Table 5: Twelve Python surfaces for one broken pipe, each run once. The answer is an errno, a return value or a mask, and none of those move between runs.

The poll result is the one that breaks a common event loop. poll reported the mask 12 both before and after the failed write: POLLOUT says the descriptor will accept a write, POLLERR says the operation will fail, and both are set. select answers the same question the same way – the descriptor is in its writable set before the write and after it – because select reports readiness for writing, and readiness only promises that the call will not block: a write to a dead pipe fails at once instead of waiting. Neither call promises that the write will succeed. A loop that treats either answer as a green light spends a wakeup on every pass writing into a dead pipe; the loop built on poll checks POLLERR first and closes the stream without a syscall, and the loop built on select has to write and catch.

What the buffered object does after a failed flush is the part most explanations get wrong. The flush raised, and the bytes it was carrying stayed in the buffer: the next small write was appended to them (write returned 1), the next flush tried the whole buffer again and raised EPIPE, and the close raised once more. A raw writer that refuses once and then accepts shows it from the other side: the second flush handed it 1,001 bytes, the refused 1,000 included. A program that catches the exception and keeps printing is therefore not starting over – it is adding to a buffer that will never leave, and pays for it at every later flush and at shutdown, which is where the exit status 120 comes from. The count of delivered bytes is not something the stream keeps; it has to be kept by the writer, which is what the package in Section 7 does.

5. The Socket Boundary: FIN, RST, Close and Shutdown

A socket has the same errno and two more states, because a TCP connection has two directions and can be ended in four ways. A peer that calls shutdown(SHUT_WR) sends a FIN and keeps reading; a peer that calls close() after reading everything also sends a FIN; a peer that closes with unread data sends a RST instead. A FIN from a full close is permission to send one more segment – which the peer’s kernel answers with a reset – and a RST is an error on the next call. A FIN from a half-close is not: that peer is still reading. That is why a server often logs two different errors for one disconnect.

Situation on a TCP loopback pairOne-byte sends, in orderWhy
Peer closes, nothing unreadok, 32, 32the first send is buffered; the reset arrives with it
Peer closes with one unread byte104, 32, 32the reset is already there: the first call reports it
This side calls shutdown(SHUT_WR)32, 32the sending direction closes locally, and the errno is 32, the same number a peer’s close gives – not ESHUTDOWN
Peer half-closes, this side sends twiceok, okthe peer read 2 bytes: a FIN is not EPIPE
Peer half-closes, then fully closesok, 32, 32the first send outlives the FIN, not the close
This side closed the socket, then sends9EBADF: the descriptor, not the peer
shutdown(SHUT_WR) called twiceok, okthe second call is accepted on Linux
recv after a successful send to a closed peereofthe FIN is readable even while sends keep succeeding
Table 6: Eight socket situations and the errno of each consecutive send, 20 ms after the peer’s action.

The row that matters most in production is the second one. A client that closes with unread data – a browser tab closed while the server is still writing, or a health check that times out mid-response – makes the kernel send a reset, and the server’s next send returns ECONNRESET. Only the send after that returns EPIPE, because by then the socket is in a state where every write is refused locally. A handler that retries on EPIPE but not on ECONNRESET will retry into a reset connection; a handler that treats both as the peer leaving will stop at the first one.

The response-writer measurement below is that shape end to end. A server writes 64 MiB in 64 KiB sends to a client that reads 1 KiB and closes. The server accepted 131,072 bytes – two sends – before the first error. With Python’s own default – SIGPIPE ignored – the program caught the error, classified it and exited 0; with SIGPIPE restored to its default, the second write killed it. The difference between a service that logs a disconnect and a service that disappears is the disposition, not the errno.

Response writerBefore the first errorErrno sequenceOutcome
Python default, client reads 1 KiB131,072 B accepted104 then 32survives, exit 0
SIGPIPE default, client reads 1 KiBnot printedfirst EPIPEkilled by signal 13
Package handling, client reads 1 KiB131,072 (65,536–262,144) B acceptedclassified as the peer leavingsurvives, exit 0
Python default, client reads 64 KiB131,072 B accepted32 in 3 of 5, 104 in 2 of 5; then 32 in all fivesurvives, exit 0
Table 7: Four response writers against a client that reads a little and closes, with the bytes accepted before the first error.

None of these numbers says the client received the bytes. The server counts what send accepted, the client received 1 KiB or 64 KiB, and the gap is the kernel buffers on both ends plus whatever was in flight. A response log that reports the server’s count as delivery is reporting the wrong end of a queue. The only count that can be called delivered is the one the client acknowledges at the application level, which is why a protocol with an application-level acknowledgement survives this failure and a protocol without one cannot.

What a refused write costs

A broken pipe is not an expensive condition to detect; it is expensive to ignore. On this host a one-byte write to a live pipe cost 2,151 ns (1,730–2,388), and the same write to a pipe with no reader cost 818 ns (807–831) once the exception was caught – less, because nothing was copied. A 64 KiB write to a live reader cost 28,890 ns (24,451–58,304); the same block written to /dev/null cost 232 ns (230–246), the price of the syscall and the copy rather than of the reader. On a socket the order reverses: a send to a live peer cost 912 ns (888–924) and a send after the peer left cost 1,594 ns (1,554–2,288), 1.75 times as much by median, because the error path unwinds more state than the delivery path copies. That multiplier is a median of five runs and carries their spread: the broken-send arm ranged wider than the live-send arm, so the multiple is approximate rather than a constant.

CallWhat happenedMedian of five runs, with the range
One byte, live pipeone byte delivered2,151 ns (1,730–2,388)
One byte, no readerEPIPE caught818 ns (807–831)
64 KiB, live readerdelivered28,890 ns (24,451–58,304)
64 KiB, /dev/nulldiscarded232 ns (230–246)
One-byte send, live socketdelivered912 ns (888–924)
One-byte send, peer goneEPIPE caught1,594 ns (1,554–2,288)
Table 8: Six calls – four pipe writes from 07_cost.py and two socket sends from 05_sockets.py – with the median cost per call of five runs and the range those runs spanned.

6. The Shell Sees 141, 1 or 0, and All Three Are Correct

A shell reports the status of the last command in a pipeline unless pipefail is set, and the last command is usually the reader – the one that succeeded. That is why a truncated pipeline is quiet by default: head exits 0 because it read what it asked for, and the producer’s death is not in the pipeline’s status at all. Setting pipefail makes the shell report the rightmost non-zero status, which for a tool killed by SIGPIPE is 141 – 128 plus the signal number. The 17 pipelines below are the same shape, with one producer replaced at a time.

Pipeline under bash unless markedStatusWhat it means
seq 1 1000000 | head -n 10head succeeded; the producer’s status is discarded
the same, with set -o pipefail141seq died on SIGPIPE
yes | head -n 1, pipefail141the canonical 141
seq 1 1000000 | head -c 0, pipefail141a reader that takes nothing still signals
cat /dev/zero | head -c 1, pipefail141cat dies, no message
dd if=/dev/zero | head -c 1, pipefail141dd dies, not a write error
seq 1 1000000 | grep -m1 5, pipefail141grep exits after its match; seq dies
python3 -c "for i in range(1000000): print(i)" | head -n 10head succeeded; Python’s traceback is on stderr
the same Python producer with pipefail1Python exited 1 with a traceback
the same producer with SIGPIPE set to default, pipefail141now it dies like seq
python3 -c "print('one line')" | head -n 1, pipefail0the producer finished before head left
a Python loop wrapped in the devnull recipe, pipefail0the recipe applied to the loop, not the flush
the devnull recipe around the final flush only, pipefail1the loop raises before the flush is reached
dash: the same seq pipeline, no pipefail0the reader’s status, as in bash
dash: seq pipeline with pipefail141dash took the option and reports the same 141
dash: false | true with pipefail1the cheapest proof the option is in force, not ignored
dash: Python pipeline with pipefail1the producer’s status again, not the reader’s
Table 9: Seventeen pipelines, the status each reported, and which process in the pipeline produced it.

The last four rows are worth a sentence because the claim that pipefail is a bash feature is repeated often enough to be taken as a limit. On this host /bin/sh is dash, and set -o pipefail is accepted there: the seq pipeline reports 141 with it and 0 without it, and false | true reports 1, which it could not if the option had been ignored. Whether a given dash accepts it is a packaging fact rather than a shell one: Debian’s 0.5.12-7 upload (2024-05-18) lists the upstream patch that implements the option, and a 0.5.12 build cut before that patch answers set: Illegal option -o pipefail and stops before the pipeline runs, so the absence shows up as an error rather than as a quietly different status. This image cannot say which build it carries – dpkg-query -W dash finds no package record and dash --version has no version to print – so the evidence here is the option’s own behaviour in the four rows above.

The two rows about the devnull recipe are easy to apply in the wrong place. The documented fix for a Python command-line tool – catch BrokenPipeError, point stdout at devnull – is usually written around the final flush, because that is where the error is explained. A producer that prints in a loop raises inside the loop, not at the final flush, so a recipe wrapped only around the flush never runs: the pipeline still reports 1. Wrapped around the loop and the flush together, the same program exits 0. The next section’s package puts that wrapper in one place so it cannot be applied to half the body.

# without pipefail, the pipeline reports the reader's status
seq 1 1000000 | head -n 1
echo "reader's status: $?"
# with pipefail, the producer's death becomes the pipeline's status
set -o pipefail
seq 1 1000000 | head -n 1
echo "pipeline status: $?"

The same two lines with a Python producer show the interpreter’s different ending: the pipeline reports 1 rather than 141, and the traceback is on stderr. A CI step that treats any non-zero status as failure will fail on both, correctly; a step that greps for 141 to detect truncation will miss every Python producer.

# a Python producer under pipefail: 1, not 141
set -o pipefail
python3 -c "for i in range(100000): print(i)" | head -n 1
echo "pipeline status: $?"

7. When a Two-Line Handler Is Not Enough

Most programs do not need a module for this. A try around the loop, the devnull redirect on BrokenPipeError, and one decision about SIGPIPE cover a command-line tool completely, and a service that only needs to stop writing needs even less. The small module in Appendix A exists for the case where a bare except stops answering: it counts the bytes the kernel accepted, names the error it was handed with one sentence per errno, sends on a socket without raising for a peer that left, and ends a tool without the interpreter’s second traceback. The one excerpt below is the counting loop everything else is built on.

"""Write a block in pieces and keep the count, because the kernel's error carries none.

``os.write`` returns the number of bytes accepted, but when it raises it returns nothing at
all: the bytes that were accepted before the reader disappeared are not in the exception. A
service that needs to log "3,412,880 of 64 MiB delivered" has to count the pieces itself.
"""

import errno
import os

CHUNK = 65536


class PipeClosed(BrokenPipeError):
    """A write that stopped early, carrying the bytes the kernel had already accepted."""

    def __init__(self, written: int, errno_number: int = errno.EPIPE) -> None:
        super().__init__(errno_number, os.strerror(errno_number))
        self.written = written
        self.errno = errno_number

    def __str__(self) -> str:
        return f"{self.written} bytes accepted before the reader left: {super().__str__()}"


def write_all(fd: int, data: bytes, chunk: int = CHUNK) -> int:
    """Write every byte, or raise PipeClosed with the count that did go out.

    A short write is not an error: it means the pipe had less room than the piece asked for,
    so the loop continues from the byte after the last one accepted.
    """
    if chunk <= 0:
        raise ValueError("chunk must be a positive number of bytes")
    sent = 0
    view = memoryview(data)
    while sent < len(view):
        piece = view[sent:sent + chunk]
        try:
            sent += os.write(fd, piece)
        except BrokenPipeError as exc:
            raise PipeClosed(sent, exc.errno or errno.EPIPE) from None
    return sent
Entry pointWhat it answers
write_all(fd, data, chunk=65536)writes every byte or raises PipeClosed carrying the count
PipeClosed.writtenthe bytes the kernel accepted before the reader left
explain(exc)names peer_closed, reset or bad_descriptor by errno, and other for an errno it does not name; a local SHUT_WR arrives as peer_closed here (Table 6), so the name is not the event
is_broken_pipe(exc)EPIPE or ECONNRESET, and nothing else
send_or_closed(sock, data)returns the bytes sent and whether the peer is gone, instead of raising
die_on_sigpipe()SIG_DFL for the duration of a block, main thread only
guarded(stream)contains a broken write inside the block and at the flush after it
exit_cleanly(stream, code)flushes, redirects to devnull if the reader left, and exits with the given code
Table 10: Eight entry points, one per question a service asks after a broken write.

The behaviour table below runs the package the way a service would, once per case: each answer is an errno, a count or an exit status, and none of those moved between runs. The tool arms give the child a stdout pipe whose reader is already gone, which is the shape of a program started from a pipeline that exited. One limit is worth stating here, because the table would otherwise suggest more than the module knows: the same 32 can come from a peer’s close (Table 6, first row) or from this side’s shutdown(SHUT_WR) (third row), where this host’s kernel reports EPIPE and not ESHUTDOWN – and from a stream socket that was never given a peer at all. So explain names the errno it was handed and never the event behind it, and a caller that knows it shut the stream down itself is the only one that can call the situation local.

Package callWhat it returnedWhat it proves
write_all, reader already gone0 bytes acceptedPipeClosed, errno 32
write_all into a 1 MiB pipe, reader never reads1,048,576 B acceptedthe whole capacity, then the error
write_all, reader takes one byte1,048,576 B acceptedthe capacity, not the one byte
guarded tool with a dead stdoutexit 0no traceback, no ignored exception
die_on_sigpipe then one writekilled by signal 13the supervisor sees a signal
exit_cleanly after a broken flushexit 0no second traceback
explain over the errnos it names, and one it does notpeer_closed, reset, bad_descriptor, otherone name per errno; the fourth input is EAGAIN, which the module leaves unnamed
send_or_closed on a half-closed and a closed peer2 bytes sent, then 0the FIN and the close are different answers
Table 11: Eight calls into the package, each run once – every answer is an errno, a count or an exit status – and the answer that distinguishes a dead reader from a dead descriptor.

The example this page runs

The output below is the package’s own run, printed by the demo file Appendix B carries whole. It makes six checks in one pass: the disposition, the count from a closed pipe, the sentence for EPIPE, the two socket answers, and a guarded stream.

disposition: ignored
write_all to a closed reader: 0 bytes, PipeClosed (errno 32)
explain: peer_closed - the reading end is gone
half-closed peer: 2 bytes sent, closed=False
closed peer: 0 bytes sent, closed=True
guarded: BrokenPipeError contained, exit 0
done: 6 checks

8. Deploying the Change: One Decision per Surface

The surfaces this page measured fail differently, so they need different changes. For a pipe in a command-line tool the decision is what the exit status should say and whether the process should end on the signal; for a pipe in a service it is whether a partial delivery is an incident; for a socket it is whether the peer left before or after its request was answered; and for a supervisor it is whether the status it sees distinguishes a truncation from a crash. The matrix below adds the two shapes that follow from those four – a batch job and a proxy – and the claims after it are the ones this page commits to.

SurfaceChange to makeWhat the change buys
Command-line tool writing to stdoutcount the bytes delivered; end with devnull and the tool’s own codea reader that left is normal, and the status still says whether the tool’s work succeeded
A worker whose contract is death on SIGPIPEset the sigpipe disposition in the main thread before threads startthe supervisor sees signal 13 and treats it as a signal, not an exception
Batch job that writes a reporttreat an accepted count below the total as a truncation and record itthe log line names how much was delivered instead of only the errno
HTTP or gRPC server writing a responseclassify reset and peer_closed before closing the connectiona client that left early is not a server error, and a half-closed client still gets its answer
Proxy or sidecar copying bytesstop on the first error, and record which side ended the streamthe second error is a symptom; the first one names the peer
Scheduler reading a pipeline’s statusenable pipefail where truncation is a failure141 becomes visible instead of being replaced by the reader’s 0
Table 12: Six surfaces and the single decision each needs after a broken pipe.

Three commitments hold across the table. Count what the kernel accepted, because the exception does not carry it and the consumer cannot report what it never saw. Decide the sigpipe disposition once, in the main thread, because a library that changes it silently changes every stream in the process. And route the shutdown flush to devnull only after the error has been recorded, because redirecting before the error would hide the failure the operator needs to see. None of these is a retry policy: a broken pipe is not transient, and a retry loop against a dead reader only produces more errors.

The platform differences are real but narrow. On Linux and macOS the number is the same (32), and the signal (13) exists on both; Apple’s own headers are the source for the macOS row of the table. Windows has no SIGPIPE: a write to a closed pipe fails with ERROR_BROKEN_PIPE (109), and a socket write after a reset reports WSAECONNRESET (10054) rather than an errno, as Microsoft’s system error tables describe. A program that hard-codes 32 will mis-handle the Windows case even though the condition is the same.

PlatformWhat a dead reader is calledHow this page knows
Linux32 / SIGPIPE 13measured on this host
macOS32 / SIGPIPE 13documented; same errno, same signal
Windows, pipe109 (ERROR_BROKEN_PIPE)documented; no signal
Windows, socket after reset10054 (WSAECONNRESET)documented; a Winsock code, not an errno
Table 13: Four platforms and the names they give the same condition, with the measured rows marked as measured.

The check that would have caught the original bug has three parts, and a pipeline that ends in a consumer which can stop early needs all of them: its producer’s status recorded, its accepted count compared with the total, and its error classified before the connection or descriptor is closed. Any one of those alone is enough to notice the problem; together they say whether the work was done or only started, which is the difference between a nightly job that is green and one that is quietly incomplete. A full filesystem loses bytes the same way, with no error at the moment the disk fills; the ENOSPC runbook follows that loss through open deleted files.

Questions This Page Answers

Is EPIPE the same as a broken pipe?

Yes: EPIPE is errno 32, its message is “Broken pipe”, and macOS gives it the same number (documented in the platform’s headers, not measured here). Python raises BrokenPipeError, a subclass of OSError that carries the same number.

Why does Python print an exception after my program has finished?

The interpreter flushes standard output while it shuts down. If the reader is gone, that flush raises after the program has returned, so the traceback has no line of yours in it and the exit status becomes 120 instead of 1. The bytes a failed flush was carrying are still in the buffer, which is why the flush at shutdown is tried again at all.

Should I set SIGPIPE back to its default?

Only if the program’s contract is a signal exit status, and only in the main thread before any worker thread writes. A library should never do it: the disposition belongs to the whole process and would change streams it does not own.

How many bytes were actually delivered when EPIPE was raised?

The exception does not say. Everything the kernel accepted before the reader left is gone with the pipe, so a writer that needs the number has to count each write’s return value; write_all does exactly that and reports it on the exception.

Why did the first send after a client closed succeed?

The send was copied into the socket’s send buffer before the peer’s reset was processed. The reset answers that segment, and the next send fails. One success is not evidence that the peer is reading.

Is a half-closed connection a broken pipe?

No. shutdown(SHUT_WR) sends a FIN that closes one direction; the peer can still receive, and this side can still read. Sending after a FIN succeeded in every run here; only a full close or a reset produced EPIPE.

Why does the server log ECONNRESET and then EPIPE?

The reset arrives first and is reported by the next operation; once it has been consumed, the socket refuses further writes with EPIPE. The first error names the peer’s action, the second is the local consequence.

Does pipefail change the exit status of head?

No. pipefail makes the shell report the rightmost non-zero status in the pipeline, so head still exits 0 but the pipeline reports the producer’s 141. Without it the pipeline reports 0 and the truncation is invisible.

Why is the exit status 1 rather than 141 for my Python producer?

Python ignores SIGPIPE at startup, so the producer raises and exits 1 with a traceback instead of dying on the signal. Restoring the default disposition makes the same pipeline report 141.

Can a write to /dev/null fail with EPIPE?

/dev/null has no reader to lose, so it does not. A write there cost a fraction of a delivered pipe write on this host, which is why the devnull recipe ends the shutdown flush without changing the work the program did.

Is EPIPE worth retrying?

No, not against the same reader. The descriptor is permanently broken once the reading end is gone: every later write returned EPIPE in every run here. A retry only makes sense on a new connection or a new consumer.

What is the shortest fix that holds?

Count the bytes the kernel accepted, decide the sigpipe disposition in the main thread, and route the shutdown flush to devnull after recording the error. That combination gives a correct log line, a meaningful exit status, and no second traceback, on a pipe and on a socket alike.

The one-line version

When a reader leaves, the bytes still in the pipe are discarded and the next write raises EPIPE without a count; a write that arrives after the reader is already gone raises at once, with nothing accepted – 65,536 bytes can be discarded by default, 1,048,576 when the pipe was enlarged. SIGPIPE is the same condition as a signal and Python ignores it, so the same syscall becomes an exception and the exit status becomes 1 or 120 instead of 141. Count what was accepted, choose the disposition once, and close the stream without a second traceback.

Other errno runbooks: Zero-Crash Python.

TechBobby Engineering. Appendix A prints the module and its 34 tests; Appendix B prints every probe behind a figure in this page.

Appendix A: The Package and Its Tests, Printed Whole

Section 7 quotes the counting loop; the folds below are the files themselves, character for character, so the package can be rebuilt from this page without a repository. The six package files come first and the five test files after them. The suite runs from the directory above pipeguard with pytest pipeguard/tests, and its count is the one quoted in the body: 34.

the entry points and the exports pipeguard/__init__.py
"""pipeguard - decide what a broken stream means, and leave nothing half-written.

The package answers three questions a service asks when a write returns EPIPE:

  * how many bytes the other side accepted before it went away (``write_all``,
    ``send_or_closed``);
  * which of the three situations produced the error - the peer closed, the peer reset, or the
    descriptor was never valid (``explain``); a local ``shutdown(SHUT_WR)`` is reported as a
    peer's close on this host, so the errno cannot carry it;
  * how a command-line tool should end without the interpreter printing a second
    traceback from its own shutdown flush (``exit_cleanly``, ``guarded``).

Nothing here turns SIGPIPE back on by default; ``die_on_sigpipe`` does that explicitly for a
worker whose contract is a signal exit status.
"""
from .errors import Broken, explain, is_broken_pipe
from .sink import PipeClosed, write_all
from .signals import die_on_sigpipe, sigpipe_disposition
from .sockets import classify_send, send_or_closed
from .stdio import exit_cleanly, guarded, redirect_to_devnull

__all__ = [
    "Broken",
    "PipeClosed",
    "classify_send",
    "die_on_sigpipe",
    "exit_cleanly",
    "explain",
    "guarded",
    "is_broken_pipe",
    "redirect_to_devnull",
    "send_or_closed",
    "sigpipe_disposition",
    "write_all",
]
the three situations and their sentences pipeguard/errors.py
"""Three situations that reach a writer as an OSError, and the sentences that separate them.

EPIPE is the number the kernel returns when a write can no longer be delivered: the reading
end is gone. ECONNRESET is the number a socket write returns when the peer answered with a
reset. EBADF is this side's own mistake. None of the three says whether the peer read what it
was sent, so the caller keeps the count - ``PipeClosed.written`` and the return value of
``send_or_closed`` exist for that.

EPIPE is also the one number that cannot say who ended the stream. On this host TCP reports a
peer's close and this side's own ``shutdown(SHUT_WR)`` with the same 32 - the socket matrix
records ``32, 32`` for the local shutdown - so ``explain`` names the errno it was handed, never
the event behind it. A caller that knows it shut the stream down itself is the only one that
can call the situation local.
"""
from __future__ import annotations

import errno
from dataclasses import dataclass

PEER_CLOSED = "peer_closed"
RESET = "reset"
BAD_DESCRIPTOR = "bad_descriptor"
OTHER = "other"


@dataclass(frozen=True)
class Broken:
    """One refusal, named, with the sentence a log line can carry."""

    reason: str
    errno: int
    hint: str


_BY_ERRNO = {
    errno.EPIPE: Broken(
        PEER_CLOSED, errno.EPIPE,
        "the reading end is gone: count what was accepted and stop writing"),
    errno.ECONNRESET: Broken(
        RESET, errno.ECONNRESET,
        "the peer sent a reset, usually because it closed with data still unread; "
        "the next write is likely to report EPIPE"),
    errno.EBADF: Broken(
        BAD_DESCRIPTOR, errno.EBADF,
        "this descriptor is closed or was never open; a retry cannot fix it"),
}


def explain(exc: BaseException) -> Broken:
    """Name the refusal a caller caught, without guessing beyond its errno.

    A local ``shutdown(SHUT_WR)`` reaches this function as EPIPE on this host, so it is named
    ``peer_closed`` like any other 32: only the caller that shut the socket down itself knows
    the event the errno cannot carry.
    """
    number = getattr(exc, "errno", None)
    if number in _BY_ERRNO:
        return _BY_ERRNO[number]
    return Broken(OTHER, int(number) if number else 0,
                  "not a broken stream this module names; re-raise it unchanged")


def is_broken_pipe(exc: BaseException) -> bool:
    """True only for the errors that mean the other side can no longer receive bytes."""
    return getattr(exc, "errno", None) in (errno.EPIPE, errno.ECONNRESET)
the disposition and the main-thread rule pipeguard/signals.py
"""SIGPIPE is a process-wide setting, and only the main thread may change it.

CPython starts with SIGPIPE ignored, so a write to a closed pipe raises instead of ending the
process. A worker that wants the shell's behaviour - death by signal 13, so the supervisor
sees a signal rather than an exit code - asks for it explicitly and briefly. A background
thread cannot: the interpreter raises ValueError, and that is checked before the call so the
error names the rule rather than the thread.
"""
from __future__ import annotations

import contextlib
import signal
import threading
from collections.abc import Iterator


def sigpipe_disposition() -> str:
    """``ignored``, ``default`` or ``handled`` - as the process has it right now."""
    current = signal.getsignal(signal.SIGPIPE)
    if current == signal.SIG_IGN:
        return "ignored"
    if current == signal.SIG_DFL:
        return "default"
    return "handled"


@contextlib.contextmanager
def die_on_sigpipe() -> Iterator[None]:
    """Let a write to a closed pipe kill this process, for the duration of the block."""
    if threading.current_thread() is not threading.main_thread():
        raise ValueError("SIGPIPE can only be changed from the main thread")
    previous = signal.getsignal(signal.SIGPIPE)
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    try:
        yield
    finally:
        signal.signal(signal.SIGPIPE, previous)
the counting write pipeguard/sink.py
"""Write a block in pieces and keep the count, because the kernel's error carries none.

``os.write`` returns the number of bytes accepted, but when it raises it returns nothing at
all: the bytes that were accepted before the reader disappeared are not in the exception. A
service that needs to log "3,412,880 of 64 MiB delivered" has to count the pieces itself.
"""
from __future__ import annotations

import errno
import os

CHUNK = 65536


class PipeClosed(BrokenPipeError):
    """A write that stopped early, carrying the bytes the kernel had already accepted."""

    def __init__(self, written: int, errno_number: int = errno.EPIPE) -> None:
        super().__init__(errno_number, os.strerror(errno_number))
        self.written = written
        self.errno = errno_number

    def __str__(self) -> str:
        return f"{self.written} bytes accepted before the reader left: {super().__str__()}"


def write_all(fd: int, data: bytes, chunk: int = CHUNK) -> int:
    """Write every byte, or raise PipeClosed with the count that did go out.

    A short write is not an error: it means the pipe had less room than the piece asked for,
    so the loop continues from the byte after the last one accepted.
    """
    if chunk <= 0:
        raise ValueError("chunk must be a positive number of bytes")
    sent = 0
    view = memoryview(data)
    while sent < len(view):
        piece = view[sent:sent + chunk]
        try:
            sent += os.write(fd, piece)
        except BrokenPipeError as exc:
            raise PipeClosed(sent, exc.errno or errno.EPIPE) from None
    return sent
send, or report the peer gone pipeguard/sockets.py
"""Sockets: EPIPE, ECONNRESET and a half-closed peer are three different answers.

A peer that calls ``shutdown(SHUT_WR)`` has closed only its writing side; this side may keep
sending, and a writer that treats that FIN as a broken connection will drop a response the
peer is still able to read. A peer that calls ``close()`` with unread data sends a reset, and
the next write reports ECONNRESET before it reports EPIPE.

The same 32 covers two events on this side of the wire: a peer's close and this side's own
``shutdown(SHUT_WR)`` both arrive as EPIPE here, and the errno has no room to say which.
"""
from __future__ import annotations

import errno
import socket

from .errors import explain

# The two refusals that mean the stream is over rather than this process misusing it. ENOTCONN
# is deliberately absent: a socket that was never given a peer raises it, and calling that "the
# peer left" would hide a local bug. On Linux an unconnected TCP socket reports EPIPE instead,
# so that case cannot be told apart from a peer's close at all.
CLOSED = (errno.EPIPE, errno.ECONNRESET)


def classify_send(exc: BaseException) -> str:
    """The name ``explain`` gives the same errno, so one error is not two stories.

    On this host a socket shut down for writing answers EPIPE, so this returns ``peer_closed``
    for that event too; the caller that called ``shutdown`` keeps that knowledge itself.
    """
    return explain(exc).reason


def send_or_closed(sock: socket.socket, data: bytes) -> tuple[int, bool]:
    """Send once; return ``(bytes_sent, peer_is_gone)`` instead of raising for a dead peer.

    A partial send is returned as a partial count: the caller decides whether to retry, and a
    socket in non-blocking mode will report EAGAIN rather than pretending the peer left. A
    socket with no peer (ENOTCONN, or EDESTADDRREQ for a datagram socket) and a closed
    descriptor (EBADF) are raised unchanged, because each is this process's mistake.
    """
    try:
        return sock.send(data), False
    except OSError as exc:
        if exc.errno in CLOSED:
            return 0, True
        raise
the devnull ending and the guarded stream pipeguard/stdio.py
"""End a program that writes to stdout without the interpreter's second traceback.

CPython flushes ``sys.stdout`` while it shuts down. If the reader is gone, that flush raises,
and because the program has already returned, the error is printed as
``Exception ignored in: <_io.TextIOWrapper name='<stdout>'>`` and the exit status becomes 120.
Catching the error inside the program is not enough: the shutdown flush runs after the catch.
The fix is to point the descriptor at devnull, so the flush that runs at shutdown has somewhere
harmless to write.
"""
from __future__ import annotations

import contextlib
import os
from collections.abc import Iterator


def redirect_to_devnull(stream) -> int:
    """Point a stream's descriptor at /dev/null and return the new descriptor."""
    descriptor = os.open(os.devnull, os.O_WRONLY)
    os.dup2(descriptor, stream.fileno())
    os.close(descriptor)
    return stream.fileno()


def exit_cleanly(stream, code: int = 0) -> None:
    """Flush, and if the reader is gone, silence the shutdown flush and exit with ``code``."""
    try:
        stream.flush()
    except BrokenPipeError:
        redirect_to_devnull(stream)
    raise SystemExit(code)


@contextlib.contextmanager
def guarded(stream) -> Iterator[object]:
    """Wrap a block that writes to a stream a reader may abandon at any moment.

    Both places the error can surface are covered: inside the block, and in the flush that
    ``exit_cleanly`` - or the interpreter's own shutdown - performs afterwards.
    """
    try:
        yield stream
    except BrokenPipeError:
        redirect_to_devnull(stream)
        return
    finally:
        try:
            stream.flush()
        except BrokenPipeError:
            redirect_to_devnull(stream)
the three situations and the ones it leaves pipeguard/tests/test_errors.py
import errno

from pipeguard.errors import BAD_DESCRIPTOR, OTHER, PEER_CLOSED, RESET, explain, is_broken_pipe


def test_epipe_is_a_peer_that_left():
    answer = explain(OSError(errno.EPIPE, "Broken pipe"))
    assert answer.reason == PEER_CLOSED
    assert answer.errno == 32
    assert "count" in answer.hint


def test_econnreset_is_a_reset():
    answer = explain(OSError(errno.ECONNRESET, "Connection reset by peer"))
    assert answer.reason == RESET
    assert "reset" in answer.hint


def test_ebadf_is_this_side_bug():
    answer = explain(OSError(errno.EBADF, "Bad file descriptor"))
    assert answer.reason == BAD_DESCRIPTOR
    assert "never open" in answer.hint


def test_an_unrelated_error_is_named_other_and_keeps_its_number():
    answer = explain(OSError(errno.EAGAIN, "Resource temporarily unavailable"))
    assert answer.reason == OTHER
    assert answer.errno == errno.EAGAIN


def test_a_non_oserror_does_not_pretend_to_be_a_pipe():
    assert explain(ValueError("nope")).reason == OTHER


def test_is_broken_pipe_covers_both_stream_errors():
    assert is_broken_pipe(OSError(errno.EPIPE, ""))
    assert is_broken_pipe(BrokenPipeError(errno.EPIPE, ""))
    assert is_broken_pipe(OSError(errno.ECONNRESET, ""))


def test_is_broken_pipe_rejects_the_rest():
    assert not is_broken_pipe(OSError(errno.EBADF, ""))
    assert not is_broken_pipe(OSError(errno.ESHUTDOWN, ""))
    assert not is_broken_pipe(OSError(errno.EAGAIN, ""))
    assert not is_broken_pipe(ValueError("nope"))
the disposition and the thread rule pipeguard/tests/test_signals.py
import signal
import threading

import pytest

from pipeguard.signals import die_on_sigpipe, sigpipe_disposition


def test_python_starts_with_sigpipe_ignored():
    assert sigpipe_disposition() == "ignored"


def test_the_block_makes_sigpipe_fatal_and_puts_it_back():
    assert sigpipe_disposition() == "ignored"
    with die_on_sigpipe():
        assert sigpipe_disposition() == "default"
        assert signal.getsignal(signal.SIGPIPE) == signal.SIG_DFL
    assert sigpipe_disposition() == "ignored"


def test_the_disposition_is_restored_after_an_error():
    with pytest.raises(RuntimeError):
        with die_on_sigpipe():
            raise RuntimeError("the work failed")
    assert sigpipe_disposition() == "ignored"


def test_a_background_thread_cannot_change_it():
    seen = []

    def change_it():
        try:
            with die_on_sigpipe():
                seen.append("changed")
        except ValueError as exc:
            seen.append(str(exc))

    thread = threading.Thread(target=change_it)
    thread.start()
    thread.join(timeout=5)
    assert seen and "main thread" in seen[0]
    assert sigpipe_disposition() == "ignored"
the count across short writes pipeguard/tests/test_sink.py
import errno
import os
import threading

import pytest

from pipeguard.sink import PipeClosed, write_all


def piped(reader_drains: bool = True):
    read_end, write_end = os.pipe()
    return read_end, write_end


def drain(read_end: int, count: int) -> bytes:
    received = b""
    while len(received) < count:
        piece = os.read(read_end, count - len(received))
        if not piece:
            break
        received += piece
    return received


def test_write_all_returns_every_byte():
    read_end, write_end = piped()
    try:
        assert write_all(write_end, b"x" * 1000) == 1000
        assert drain(read_end, 1000) == b"x" * 1000
    finally:
        os.close(read_end)
        os.close(write_end)


def test_write_all_chunks_without_changing_the_bytes():
    read_end, write_end = piped()
    payload = bytes(range(200)) * 10
    try:
        assert write_all(write_end, payload, chunk=7) == len(payload)
        assert drain(read_end, len(payload)) == payload
    finally:
        os.close(read_end)
        os.close(write_end)


def test_write_all_accepts_a_zero_length_payload():
    read_end, write_end = piped()
    try:
        assert write_all(write_end, b"") == 0
    finally:
        os.close(read_end)
        os.close(write_end)


def test_a_zero_chunk_is_a_usage_error():
    read_end, write_end = piped()
    try:
        with pytest.raises(ValueError):
            write_all(write_end, b"x", chunk=0)
    finally:
        os.close(read_end)
        os.close(write_end)


def test_a_closed_reader_raises_with_the_count():
    read_end, write_end = piped()
    os.close(read_end)
    try:
        with pytest.raises(PipeClosed) as caught:
            write_all(write_end, b"x" * 10)
        assert caught.value.written == 0
        assert caught.value.errno == errno.EPIPE
    finally:
        os.close(write_end)


def test_the_range_advances_across_short_writes():
    read_end, write_end = piped()
    payload = b"y" * 30000
    reader = threading.Thread(target=lambda: drain(read_end, len(payload)))
    reader.start()
    try:
        assert write_all(write_end, payload, chunk=4096) == len(payload)
    finally:
        reader.join(timeout=5)
        os.close(read_end)
        os.close(write_end)


def test_the_message_carries_the_count_and_the_errno():
    closed = PipeClosed(4096)
    text = str(closed)
    assert "4096 bytes accepted" in text
    assert "Broken pipe" in text


def test_a_closed_descriptor_is_not_reported_as_a_closed_reader():
    read_end, write_end = piped()
    os.close(read_end)
    os.close(write_end)
    with pytest.raises(OSError) as caught:
        write_all(write_end, b"x")
    assert caught.value.errno == errno.EBADF
    assert not isinstance(caught.value, PipeClosed)
half-close and close pipeguard/tests/test_sockets.py
import errno
import socket

import pytest

from pipeguard.sockets import classify_send, send_or_closed


def test_a_live_peer_receives_the_bytes():
    left, right = socket.socketpair()
    try:
        sent, closed = send_or_closed(left, b"abc")
        assert (sent, closed) == (3, False)
        assert right.recv(16) == b"abc"
    finally:
        left.close()
        right.close()


def test_a_closed_peer_is_reported_not_raised():
    left, right = socket.socketpair()
    right.close()
    try:
        closed = False
        for _ in range(4):
            sent, closed = send_or_closed(left, b"x" * 4096)
            if closed:
                break
        assert closed is True
        assert sent == 0
    finally:
        left.close()


def test_a_half_closed_peer_still_receives():
    left, right = socket.socketpair()
    try:
        right.shutdown(socket.SHUT_WR)
        sent, closed = send_or_closed(left, b"abc")
        assert (sent, closed) == (3, False)
        assert right.recv(16) == b"abc"
    finally:
        left.close()
        right.close()


def test_epipe_is_classified_as_a_peer_that_left():
    assert classify_send(OSError(errno.EPIPE, "")) == "peer_closed"


def test_a_reset_is_classified_separately():
    assert classify_send(OSError(errno.ECONNRESET, "")) == "reset"


def test_another_error_keeps_its_identity():
    assert classify_send(OSError(errno.EAGAIN, "")) == "other"


def test_a_local_shutdown_arrives_as_a_peer_close():
    """A real SHUT_WR on this host reaches the caller as EPIPE, so it is named peer_closed."""
    listener = socket.socket()
    listener.bind(("127.0.0.1", 0))
    listener.listen(1)
    client = socket.socket()
    client.connect(listener.getsockname())
    server, _ = listener.accept()
    try:
        server.shutdown(socket.SHUT_WR)
        with pytest.raises(OSError) as caught:
            server.send(b"x")
        assert caught.value.errno == errno.EPIPE
        assert classify_send(caught.value) == "peer_closed"
    finally:
        client.close()
        server.close()
        listener.close()


def test_an_unconnected_socket_is_a_local_bug_not_a_quiet_close():
    orphan = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        with pytest.raises(OSError) as caught:
            send_or_closed(orphan, b"x")
        # A datagram socket with no peer answers EDESTADDRREQ, not "the peer left".
        assert caught.value.errno == errno.EDESTADDRREQ
    finally:
        orphan.close()


def test_an_unrelated_error_is_raised_unchanged():
    left, right = socket.socketpair()
    left.close()
    try:
        sent, closed = send_or_closed(left, b"x")
    except OSError as exc:
        assert exc.errno == errno.EBADF
    else:
        raise AssertionError("a closed socket must not be reported as a quiet close")
    finally:
        right.close()
the guarded stream and the devnull ending pipeguard/tests/test_stdio.py
import io
import os

import pytest

from pipeguard.stdio import exit_cleanly, guarded, redirect_to_devnull


def broken_stream() -> io.BufferedWriter:
    read_end, write_end = os.pipe()
    os.close(read_end)
    return io.open(write_end, "wb", buffering=1024, closefd=True)


def test_redirect_points_the_descriptor_at_devnull():
    stream = broken_stream()
    redirect_to_devnull(stream)
    stream.write(b"x" * 10)
    stream.flush()


def test_exit_cleanly_raises_system_exit_with_the_code():
    stream = broken_stream()
    with pytest.raises(SystemExit) as caught:
        exit_cleanly(stream, code=3)
    assert caught.value.code == 3


def test_exit_cleanly_moves_a_broken_stream_to_devnull():
    stream = broken_stream()
    before = os.fstat(stream.fileno()).st_dev, os.fstat(stream.fileno()).st_ino
    stream.write(b"x" * 100)
    with pytest.raises(SystemExit):
        exit_cleanly(stream, code=0)
    after = os.fstat(stream.fileno()).st_dev, os.fstat(stream.fileno()).st_ino
    assert before != after


def test_guarded_swallows_a_broken_write_inside_the_block(capfd):
    stream = broken_stream()
    with guarded(stream):
        stream.write(b"x" * 100)
        stream.flush()
    stream.write(b"y")


def test_guarded_repoints_the_stream_after_the_error():
    stream = broken_stream()
    before = os.fstat(stream.fileno()).st_dev, os.fstat(stream.fileno()).st_ino
    with guarded(stream):
        stream.write(b"x" * 100)
        stream.flush()
    after = os.fstat(stream.fileno()).st_dev, os.fstat(stream.fileno()).st_ino
    assert before != after


def test_guarded_leaves_a_healthy_stream_alone():
    read_end, write_end = os.pipe()
    stream = io.open(write_end, "wb", buffering=1024)
    try:
        with guarded(stream):
            stream.write(b"abc")
        os.set_blocking(read_end, False)
        assert os.read(read_end, 16) == b"abc"
    finally:
        os.close(read_end)
        stream.close()

Appendix B: The Probes, Printed Whole

These are the files that produced every figure in Tables 2 through 11, and the counts the body quotes about its own tree. Each writes one record under results/ holding the runs its table quotes – five for a timing row, one for an errno – and the helper they share is printed first. Table 2 comes from 01_facts.py; Table 3 from 02_sigpipe.py; Table 4 from 03_buffer.py; Table 5 from 04_python.py; Table 6, and the two socket sends of Table 8, from 05_sockets.py; Table 9 from 06_shell.py; the four pipe rows of Table 8 from 07_cost.py; Table 7 from 08_repro.py; Tables 10 and 11 from 11_package.py; and the test, line and file counts from 09_counts.py, which runs the suite it counts. The demo file whose output Section 7 prints comes last.

one record, five runs when a row asks for them sandbox/probelib.py
"""Shared helpers for the probes: one JSON record per probe, as many runs as the arm asks.

An arm is a list of run records built by calling the same function again, so a figure printed
with a range is a range over independent executions rather than one observation described
loosely. An errno, an exit status or a poll mask answers the same on the tenth run and is run
once; a reader's pace, a cost per call or a response racer moves and is run five times.
"""
from __future__ import annotations

import json
import os
import pathlib
import signal
import statistics
import subprocess
import sys
import time

PY = sys.executable
HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"

READY = b"ready\n"


def save(name: str, payload: dict) -> pathlib.Path:
    RESULTS.mkdir(parents=True, exist_ok=True)
    path = RESULTS / f"{name}.json"
    path.write_text(json.dumps(payload, indent=1, sort_keys=False) + "\n", encoding="utf-8")
    return path


def repeat(label: str, function, times: int = 5) -> dict:
    """Run one arm the number of times its row needs and keep each run's own record."""
    runs = []
    for _ in range(times):
        runs.append(function())
    return {"label": label, "runs": runs}


def median(values: list[float]) -> float:
    return statistics.median(values)


def band(values: list[float]) -> dict:
    return {"median": median(values), "min": min(values), "max": max(values),
            "runs": [round(value, 3) for value in values]}


def host_facts() -> dict:
    import platform
    return {
        "kernel": platform.release(),
        "python": platform.python_version(),
        "machine": platform.machine(),
        "cpus": os.cpu_count(),
        "page_size": os.sysconf("SC_PAGE_SIZE"),
        "tmp_fstype": filesystem("/tmp"),
        "work_fstype": filesystem(str(HERE)),
        "sh": os.path.realpath("/bin/sh"),
        "coreutils": shell_output("ls", "--version").splitlines()[0],
        "proc_version": pathlib.Path("/proc/version").read_text().strip(),
    }


def filesystem(path: str) -> str:
    best = ""
    kind = "unknown"
    for line in pathlib.Path("/proc/mounts").read_text().splitlines():
        parts = line.split()
        if len(parts) < 3:
            continue
        mount, fstype = parts[1], parts[2]
        if path == mount or path.startswith(mount.rstrip("/") + "/"):
            if len(mount) >= len(best):
                best, kind = mount, fstype
    return kind


def shell_output(*argv: str) -> str:
    return subprocess.run(argv, capture_output=True, text=True).stdout.strip()


def signal_mask(pid: int | None = None) -> dict:
    """The kernel's own record of which signals a process ignores and handles."""
    status = pathlib.Path(f"/proc/{pid}/status" if pid else "/proc/self/status").read_text()
    out = {}
    for line in status.splitlines():
        if line.startswith(("SigIgn:", "SigCgt:", "SigBlk:")):
            name, _, value = line.partition(":")
            out[name.rstrip(":")] = value.strip()
    return out


def ignored(mask: str, number: int) -> bool:
    return bool(int(mask, 16) & (1 << (number - 1)))


def run_python(code: str, timeout: float = 30, stdout=None, stdin=None) -> dict:
    """Run a snippet, keeping the answer a reader would need: rc, signal, streams."""
    started = time.perf_counter()
    result = subprocess.run([PY, "-c", code], capture_output=True, timeout=timeout,
                            stdout=stdout, stdin=stdin) if stdout is None else \
        subprocess.run([PY, "-c", code], stdout=stdout, stderr=subprocess.PIPE,
                       timeout=timeout, stdin=stdin)
    elapsed = time.perf_counter() - started
    return {
        "rc": result.returncode,
        "signal": -result.returncode if result.returncode < 0 else None,
        "stdout_bytes": len(result.stdout or b"") if stdout is None else -1,
        "stderr": (result.stderr or b"").decode("utf-8", "replace")[:400],
        "seconds": round(elapsed, 3),
    }


def broken_stdout_run(code: str, timeout: float = 30) -> dict:
    """Give the child a stdout pipe whose read end is already closed, then run it."""
    read_end, write_end = os.pipe()
    os.close(read_end)
    try:
        return run_python(code, timeout=timeout, stdout=write_end)
    finally:
        os.close(write_end)


def pipe_run(code: str, read_bytes: int, timeout: float = 30) -> dict:
    """Give the child a pipe for stdout, read exactly N bytes here, then close the reader."""
    read_end, write_end = os.pipe()
    started = time.perf_counter()
    process = subprocess.Popen([PY, "-c", code], stdout=write_end, stderr=subprocess.PIPE)
    os.close(write_end)
    received = b""
    try:
        while len(received) < read_bytes:
            chunk = os.read(read_end, read_bytes - len(received))
            if not chunk:
                break
            received += chunk
    finally:
        os.close(read_end)
    _, stderr = process.communicate(timeout=timeout)
    elapsed = time.perf_counter() - started
    answer = {}
    for line in stderr.decode("utf-8", "replace").splitlines():
        if line.startswith("{"):
            try:
                answer = json.loads(line)
            except json.JSONDecodeError:
                pass
    return {
        "rc": process.returncode,
        "signal": -process.returncode if process.returncode < 0 else None,
        "read_bytes": len(received),
        "writer_bytes": answer.get("bytes"),
        "writer_chunks": answer.get("chunks"),
        "writer_errno": answer.get("errno"),
        "writer_type": answer.get("type"),
        "stderr_tail": stderr.decode("utf-8", "replace").strip().splitlines()[-1:],
        "seconds": round(elapsed, 3),
    }


def last_line(text: str) -> str:
    lines = [line for line in text.strip().splitlines() if line.strip()]
    return lines[-1] if lines else ""


SIGPIPE = int(signal.SIGPIPE)


def header(name: str, notes: dict, arms: list[dict], documented: dict | None = None) -> dict:
    return {"probe": name, "host": host_facts(), "notes": notes, "arms": arms,
            "documented": documented or {}}
the host, the masks, and the capacities sandbox/01_facts.py
"""What this host says about a pipe, and what the standards say: the two kept apart."""
from __future__ import annotations

import errno
import fcntl
import os
import re
import signal
import subprocess
import sys

import probelib

LINUX = sys.platform == "linux"
F_GETPIPE_SZ = getattr(fcntl, "F_GETPIPE_SZ", 1032)
F_SETPIPE_SZ = getattr(fcntl, "F_SETPIPE_SZ", 1031)
PIPE_CAPACITY_DEFAULT = 65536
PIPE_CAPACITY_LARGE = 1048576


def pipe_size(request: int | None = None) -> tuple[int, int]:
    read_end, write_end = os.pipe()
    try:
        if request is not None:
            fcntl.fcntl(write_end, F_SETPIPE_SZ, request)
        size = fcntl.fcntl(write_end, F_GETPIPE_SZ)
        block = os.fpathconf(write_end, "PC_PIPE_BUF")
        return size, block
    finally:
        os.close(read_end)
        os.close(write_end)


def capacity_by_filling(request: int | None) -> int:
    """Fill the pipe without a reader until EAGAIN: the capacity the kernel enforces."""
    read_end, write_end = os.pipe()
    os.set_blocking(write_end, False)
    try:
        if request is not None:
            fcntl.fcntl(write_end, F_SETPIPE_SZ, request)
        total = 0
        while True:
            try:
                total += os.write(write_end, b"x" * 65536)
            except BlockingIOError:
                return total
    finally:
        os.close(read_end)
        os.close(write_end)


def write_after_capacity(request: int | None, payload: int) -> dict:
    """A blocking write larger than the pipe: how much goes in before it blocks?"""
    read_end, write_end = os.pipe()
    try:
        if request is not None:
            fcntl.fcntl(write_end, F_SETPIPE_SZ, request)
        os.set_blocking(write_end, False)
        try:
            sent = os.write(write_end, b"x" * payload)
            return {"written": sent, "blocked": False}
        except BlockingIOError as exc:
            return {"written": None, "blocked": True, "characters": exc.characters_written}
    finally:
        os.close(read_end)
        os.close(write_end)


def mask_value(status: str, name: str) -> str:
    """A /proc status mask, whatever whitespace the kernel used after the colon."""
    match = re.search(rf"^{name}:\s*([0-9a-fA-F]+)", status, re.M)
    return match.group(1) if match else "0"


def main() -> None:
    if not LINUX:
        raise SystemExit("01_facts reads /proc/self/status and /proc/sys/fs, which only Linux "
                         "provides")
    default_size, block = pipe_size()
    large_size, _ = pipe_size(PIPE_CAPACITY_LARGE)
    small_size, _ = pipe_size(4096)

    child = subprocess.run(
        [sys.executable, "-c",
         "import os,signal,sys;print(signal.getsignal(signal.SIGPIPE));"
         "print(open('/proc/self/status').read().split('SigIgn:')[1].split()[0])"],
        capture_output=True, text=True).stdout.strip().splitlines()
    # Builtins only: /proc/self has to belong to the shell, not to a tool it execs.
    shell_mask = subprocess.run(
        ["/bin/sh", "-c",
         "exec 3</proc/self/status; while IFS= read -r line <&3; do case $line in "
         "SigIgn*|SigBlk*) echo \"$line\";; esac; done"],
        capture_output=True, text=True).stdout
    own = probelib.signal_mask()
    reset_mask = subprocess.run(
        [sys.executable, "-c",
         "import signal,os;signal.signal(signal.SIGPIPE,signal.SIG_DFL);"
         "print(open('/proc/self/status').read().split('SigIgn:')[1].split()[0])"],
        capture_output=True, text=True).stdout.strip()

    mask_after_reset = probelib.run_python(
        "import signal;signal.signal(signal.SIGPIPE, signal.SIG_DFL);"
        "print(signal.getsignal(signal.SIGPIPE))")

    arms = [
        probelib.repeat("pipe_capacity_default", lambda: {
            "requested": None, "capacity": capacity_by_filling(None)}),
        probelib.repeat("pipe_capacity_one_mib", lambda: {
            "requested": PIPE_CAPACITY_LARGE, "capacity": capacity_by_filling(PIPE_CAPACITY_LARGE)}),
        probelib.repeat("pipe_capacity_four_kib", lambda: {
            "requested": 4096, "capacity": capacity_by_filling(4096)}),
        probelib.repeat("write_65536_into_empty_pipe", lambda: write_after_capacity(None, 65536)),
        probelib.repeat("write_65537_into_empty_pipe", lambda: write_after_capacity(None, 65537)),
        probelib.repeat("write_131072_into_mask_pipe",
                        lambda: write_after_capacity(None, 131072)),
    ]

    notes = {
        "python_sigpipe_disposition": child[0] if child else None,
        "python_sigign_mask": child[1] if len(child) > 1 else None,
        "inherited_sigign_mask": own.get("SigIgn"),
        "sigpipe_bit_set_in_python": probelib.ignored(own["SigIgn"], probelib.SIGPIPE),
        "sigpipe_bit_set_in_sh": probelib.ignored(mask_value(shell_mask, "SigIgn"), 13),
        "sigign_after_sig_dfl": reset_mask,
        "sigpipe_bit_set_after_sig_dfl": probelib.ignored(reset_mask, 13),
        "after_reset_getsignal": mask_after_reset["stdout_bytes"] and "0",
        "pipe_default_capacity": default_size,
        "pipe_large_capacity": large_size,
        "pipe_small_capacity": small_size,
        "pipe_block": block,
        "pipe_max_size": int(open("/proc/sys/fs/pipe-max-size").read()),
        "pipe_user_pages_soft": int(open("/proc/sys/fs/pipe-user-pages-soft").read()),
        "epipe_value": errno.EPIPE,
        "epipe_name": errno.errorcode[errno.EPIPE],
        "epipe_message": os.strerror(errno.EPIPE),
        "eagain_value": errno.EAGAIN,
        "econnreset_value": errno.ECONNRESET,
        "econnreset_message": os.strerror(errno.ECONNRESET),
        "epipe_is_32": errno.EPIPE == 32,
        "sigpipe_number": int(signal.SIGPIPE),
        "sigpipe_name": signal.Signals(signal.SIGPIPE).name,
        "sh_path": os.path.realpath("/bin/sh"),
        "sh_sigign_mask": mask_value(shell_mask, "SigIgn"),
    }

    documented = {
        "posix": {
            "rule": "A write to a pipe with no reader raises EPIPE and generates SIGPIPE for the "
                    "writing thread; the disposition decides whether the process dies or the "
                    "call returns -1.",
            "source": "POSIX.1-2017, write(), ERRORS [EPIPE]; Signal Concepts.",
        },
        "linux": {
            "rule": "EPIPE is 32 on Linux; SIGPIPE is signal 13 and its default disposition "
                    "terminates the process.",
            "source": "signal(7), errno(3) on the host's man pages.",
        },
        "python": {
            "rule": "CPython sets SIGPIPE to SIG_IGN at startup so that a write to a closed "
                    "pipe raises BrokenPipeError instead of ending the interpreter, and the "
                    "documented recipe for a command-line tool is to catch it, point stdout at "
                    "devnull and exit.",
            "source": "Python documentation, signal module note and 'Note on SIGPIPE'; "
                      "PEP 475 does not apply (EPIPE is not an interrupted call).",
            "exit_code_note": "The interpreter sets exit status 120 when flushing a standard "
                              "stream fails at shutdown.",
        },
        "windows": {
            "broken_pipe_error": 109,
            "wsaeconnreset": 10054,
            "rule": "A write to a pipe whose other end closed fails with ERROR_BROKEN_PIPE "
                    "(109); a socket write after a reset fails with WSAECONNRESET (10054). "
                    "There is no SIGPIPE.",
            "source": "Microsoft Learn, System Error Codes 0-499 and Windows Sockets error codes.",
        },
        "macos": {
            "epipe": 32,
            "rule": "EPIPE is 32 and SIGPIPE keeps its default disposition unless the program "
                    "changes it.",
            "source": "XNU errno.h and signal.h, quoted from the platform's own headers.",
        },
    }

    probelib.save("01_facts", probelib.header("01_facts", notes, arms, documented))
    print("sigign python:", notes["python_sigign_mask"],
          "bit set:", notes["sigpipe_bit_set_in_python"], "| after SIG_DFL:",
          notes["sigign_after_sig_dfl"], "bit set:", notes["sigpipe_bit_set_after_sig_dfl"])
    print("capacities:", default_size, large_size, small_size, "block", block)
    for arm in arms:
        print(arm["label"], [run.get("capacity", run.get("written")) for run in arm["runs"]])


if __name__ == "__main__":
    main()
one write, fourteen dispositions sandbox/02_sigpipe.py
"""One write, two dispositions: what a dead reader does to a process on this host."""
from __future__ import annotations

import probelib

WRITE_128K = 'import os; os.write(1, b"x" * 131072)'
WRITE_4K = 'import os; os.write(1, b"x" * 4096)'

CODES = {
    # The same syscall, with the disposition Python starts with and with the one the shell has.
    "write_default": WRITE_128K,
    "write_sig_dfl": 'import os, signal; signal.signal(signal.SIGPIPE, signal.SIG_DFL);'
                     'os.write(1, b"x" * 131072)',
    "write_sig_dfl_4k": 'import os, signal; signal.signal(signal.SIGPIPE, signal.SIG_DFL);'
                        'os.write(1, b"x" * 4096)',
    "write_sig_dfl_small_1b": 'import os, signal; signal.signal(signal.SIGPIPE, signal.SIG_DFL);'
                              'os.write(1, b"x")',
    # The buffered stream: a small print is held until exit, a large one flushes inside print.
    "print_small": 'print("x" * 1000)',
    "print_large": 'print("x" * 200000)',
    "print_small_caught": 'try:\n print("x" * 1000)\nexcept BrokenPipeError:\n pass',
    "print_flush_caught": 'import sys\ntry:\n print("x" * 1000); sys.stdout.flush()\n'
                          'except BrokenPipeError:\n pass',
    # The two documented endings for a command-line tool.
    "devnull_recipe": 'import os, sys\n'
                      'sys.stdout.write("x" * 1000)\n'
                      'try:\n sys.stdout.flush()\n'
                      'except BrokenPipeError:\n'
                      ' devnull = os.open(os.devnull, os.O_WRONLY)\n'
                      ' os.dup2(devnull, sys.stdout.fileno())\n'
                      ' sys.exit(0)',
    "devnull_then_raise": 'import os, sys\n'
                          'sys.stdout.write("x" * 1000)\n'
                          'try:\n sys.stdout.flush()\n'
                          'except BrokenPipeError:\n'
                          ' devnull = os.open(os.devnull, os.O_WRONLY)\n'
                          ' os.dup2(devnull, sys.stdout.fileno())\n'
                          ' raise SystemExit(3)',
    "os_exit_recipe": 'import os, sys\n'
                      'sys.stdout.write("x" * 1000)\n'
                      'try:\n sys.stdout.flush()\n'
                      'except BrokenPipeError:\n os._exit(1)',
    # What the buffered object does once a flush has already failed.
    "write_after_failed_flush": 'import sys\n'
                                'try:\n sys.stdout.write("x" * 1000); sys.stdout.flush()\n'
                                'except BrokenPipeError:\n'
                                ' try:\n  sys.stdout.write("y")\n'
                                ' except Exception as exc:\n'
                                '  raise SystemExit(type(exc).__name__ + ": " + str(exc))',
    # Two writes in a row, and the errno the second one carries.
    "write_twice": 'import os, errno\n'
                   'for _ in range(2):\n'
                   ' try:\n  os.write(1, b"x" * 4096)\n'
                   ' except OSError as exc:\n'
                   '  print(exc.errno, exc.strerror, file=__import__("sys").stderr)',
    # A signal disposition is a process-wide setting owned by the main thread.
    "signal_from_thread": 'import signal, threading\n'
                          'def set_it():\n'
                          ' try:\n  signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n'
                          ' except Exception as exc:\n'
                          '  print(type(exc).__name__ + ": " + str(exc), file=__import__("sys").stderr)\n'
                          'threading.Thread(target=set_it).start()\n'
                          'import time; time.sleep(0.1)',
}


def main() -> None:
    arms = []
    for label, code in CODES.items():
        # An exit status and a signal number are deterministic on this host, so one run each.
        arms.append(probelib.repeat(label, lambda code=code: probelib.broken_stdout_run(code),
                                    times=1))
    notes = {
        "codes": {label: code for label, code in CODES.items()},
        "python_sigpipe": 1,
        "sigpipe_number": probelib.SIGPIPE,
        "runs_per_arm": 1,
        "output_note": "stdout of every arm is a pipe whose read end was closed before the "
                       "child ran, so the first write has no reader.",
    }
    probelib.save("02_sigpipe", probelib.header("02_sigpipe", notes, arms))
    for arm in arms:
        first = arm["runs"][0]
        print(f"{arm['label']:26s} rc={first['rc']:>4} sig={first['signal']} "
              f"stderr={probelib.last_line(first['stderr'])[:80]!r}")
        print("    rc per run:", [run["rc"] for run in arm["runs"]])


if __name__ == "__main__":
    main()
how much the pipe accepts sandbox/03_buffer.py
"""How many bytes a writer is allowed to hand over before the dead reader is reported.

The writer writes fixed-size blocks to its stdout pipe and reports, on stderr, how many bytes
the kernel accepted before EPIPE. The parent reads a fixed number of bytes and then closes the
read end - the shape of ``producer | head -c N``.
"""
from __future__ import annotations

import fcntl
import json
import os
import subprocess
import sys
import time

import probelib

LINUX = sys.platform == "linux"
F_GETPIPE_SZ = getattr(fcntl, "F_GETPIPE_SZ", 1032)
F_SETPIPE_SZ = getattr(fcntl, "F_SETPIPE_SZ", 1031)

WRITER = '''
import json, os, sys
chunk = {chunk}
total = 0
chunks = 0
errno = None
kind = None
try:
    while True:
        written = os.write(1, b"x" * chunk)
        total += written
        chunks += 1
except OSError as exc:
    errno = exc.errno
    kind = type(exc).__name__
print(json.dumps({{"bytes": total, "chunks": chunks, "errno": errno, "type": kind}}),
      file=sys.stderr)
'''


def run(chunk: int, read_bytes: int, pipe_size: int | None, hold: float = 0.05) -> dict:
    read_end, write_end = os.pipe()
    if pipe_size is not None:
        fcntl.fcntl(write_end, F_SETPIPE_SZ, pipe_size)
    capacity = fcntl.fcntl(write_end, F_GETPIPE_SZ)
    process = subprocess.Popen([sys.executable, "-c", WRITER.format(chunk=chunk)],
                               stdout=write_end, stderr=subprocess.PIPE)
    os.close(write_end)
    received = b""
    started = time.perf_counter()
    try:
        while len(received) < read_bytes:
            piece = os.read(read_end, min(65536, read_bytes - len(received)))
            if not piece:
                break
            received += piece
        # A reader that reads its share, works for a moment, then goes away.
        if hold:
            time.sleep(hold)
    finally:
        os.close(read_end)
    _, stderr = process.communicate(timeout=30)
    elapsed = time.perf_counter() - started
    answer = {}
    for line in stderr.decode("utf-8", "replace").splitlines():
        if line.startswith("{"):
            answer = json.loads(line)
    accepted = answer.get("bytes")
    return {
        "rc": process.returncode,
        "chunk": chunk,
        "read_bytes": len(received),
        "capacity": capacity,
        "accepted": accepted,
        "lost": None if accepted is None else accepted - len(received),
        "chunks": answer.get("chunks"),
        "errno": answer.get("errno"),
        "kind": answer.get("type"),
        "seconds": round(elapsed, 3),
    }


def main() -> None:
    if not LINUX:
        raise SystemExit("03_buffer raises the pipe size with F_SETPIPE_SZ, which only Linux "
                         "provides")
    arms: list[dict] = []
    plan = [
        ("reader_takes_nothing_holds_50ms", 65536, 0, None),
        ("reader_closed_before_writer_starts", 1, 0, None),
        ("reader_takes_one_byte", 65536, 1, None),
        ("reader_takes_one_block", 65536, 65536, None),
        ("reader_takes_two_blocks", 65536, 131072, None),
        ("one_byte_blocks_one_byte", 1, 1, None),
        ("four_kib_blocks_one_byte", 4096, 1, None),
        ("one_byte_blocks_one_byte_large_pipe", 1, 1, 1048576),
        ("four_kib_blocks_one_byte_large_pipe", 4096, 1, 1048576),
        ("one_mib_block_large_pipe", 1048576, 1, 1048576),
        ("reader_takes_nothing_large_pipe", 65536, 0, 1048576),
    ]
    for label, chunk, read_bytes, pipe_size in plan:
        hold = 0.0 if label == "reader_closed_before_writer_starts" else 0.05
        if hold == 0.0:
            # The reader is gone before the writer has started: close immediately, no sleep.
            arms.append(probelib.repeat(
                label, lambda chunk=chunk, read_bytes=read_bytes, pipe_size=pipe_size:
                run(chunk, read_bytes, pipe_size, hold=0.0)))
            continue
        arms.append(probelib.repeat(
            label, lambda chunk=chunk, read_bytes=read_bytes, pipe_size=pipe_size:
            run(chunk, read_bytes, pipe_size)))

    notes = {
        "shape": "producer writes blocks to a pipe; the reader takes N bytes, waits 50 ms and "
                 "closes the read end; the producer reports the bytes the kernel accepted.",
        "default_capacity": 65536,
        "large_capacity": 1048576,
        "delay_seconds": 0.05,
    }
    probelib.save("03_buffer", probelib.header("03_buffer", notes, arms))
    for arm in arms:
        runs = arm["runs"]
        accepted = [run["accepted"] for run in runs]
        lost = [run["lost"] for run in runs]
        print(f"{arm['label']:38s} capacity={runs[0]['capacity']:>8} accepted={accepted} "
              f"lost={lost} errno={runs[0]['errno']}")


if __name__ == "__main__":
    main()
buffers, pollers and descriptors sandbox/04_python.py
"""Python's own surface: buffered writers, pollers, and what a broken descriptor answers next.

Every arm here is deterministic - an errno and a poll mask do not move between runs - so each is
run once rather than repeated. The one arm that depends on an interpreter detail (whether a
failed flush keeps its bytes) is settled with a raw writer that refuses once and then accepts,
which makes the answer visible as the size of the next write instead of a timing.
"""
from __future__ import annotations

import errno
import io
import os
import select
import socket
import sys

import probelib


def _close(fd: int) -> None:
    if fd >= 0:
        try:
            os.close(fd)
        except OSError:
            pass


def fresh_pipe(close_reader: bool = True) -> tuple[int, int]:
    read_end, write_end = os.pipe()
    if close_reader:
        _close(read_end)
        read_end = -1
    return read_end, write_end


def _flush(stream) -> str:
    try:
        stream.flush()
        return "ok"
    except OSError as exc:
        return type(exc).__name__


def _flush_errno(stream):
    try:
        stream.flush()
        return None
    except OSError as exc:
        return exc.errno


def buffered_write_then_flush() -> dict:
    read_end, write_end = fresh_pipe()
    stream = io.open(write_end, "wb", buffering=8192, closefd=False)
    answer: dict = {}
    try:
        answer["buffered_write"] = stream.write(b"x" * 1000)
        answer["flush"] = _flush(stream)
        try:
            stream.write(b"y")
            answer["second_write"] = "accepted"
        except Exception as exc:  # noqa: BLE001 - the point is the type, not the message
            answer["second_write"] = type(exc).__name__
        answer["second_flush"] = _flush(stream)
    finally:
        try:
            stream.close()
            answer["close"] = "ok"
        except OSError as exc:
            answer["close"] = type(exc).__name__
        _close(read_end)
        os.close(write_end)
    return answer


class _RefusingRaw(io.RawIOBase):
    """A raw writer that refuses its first write and accepts the next one.

    A pipe whose reader is gone refuses everything, so it cannot show whether a failed flush
    kept its bytes. This can: the size of the write the raw object receives next is the number
    of bytes the buffer was still holding.
    """

    def __init__(self) -> None:
        self.sizes: list[int] = []
        self.refusals = 1

    def writable(self) -> bool:
        return True

    def write(self, data) -> int:  # type: ignore[override]
        self.sizes.append(len(data))
        if self.refusals:
            self.refusals -= 1
            raise OSError(errno.EPIPE, "Broken pipe")
        return len(data)


def buffered_flush_retention() -> dict:
    raw = _RefusingRaw()
    stream = io.BufferedWriter(raw, buffer_size=8192)
    try:
        first = stream.write(b"x" * 1000)
        first_flush = _flush_errno(stream)
        second = stream.write(b"y")
        second_flush = _flush_errno(stream)
        return {
            "first_write": first,
            "first_flush_errno": first_flush,
            "second_write": second,
            "second_flush_errno": second_flush,
            "raw_calls": list(raw.sizes),
            "delivered_on_second_flush": raw.sizes[-1] if len(raw.sizes) > 1 else 0,
        }
    finally:
        try:
            stream.close()
        except (OSError, ValueError):
            pass


def text_write_then_flush() -> dict:
    read_end, write_end = fresh_pipe()
    stream = io.open(write_end, "w", encoding="utf-8", buffering=8192, closefd=False)
    try:
        written = stream.write("x" * 1000)
        answer = {"text_write": written}
        try:
            stream.flush()
            answer["flush"] = "ok"
        except OSError as exc:
            answer["flush"] = type(exc).__name__
            answer["errno"] = exc.errno
    finally:
        try:
            stream.close()
        except OSError:
            pass
        _close(read_end)
        os.close(write_end)
    return answer


def write_is_sticky() -> dict:
    read_end, write_end = fresh_pipe()
    try:
        first = _write_errno(write_end)
        outcomes = [_write_errno(write_end) for _ in range(100)]
        return {"first": first, "distinct": sorted({str(value) for value in outcomes}),
                "all_epipe": outcomes.count(32) == 100}
    finally:
        _close(read_end)
        os.close(write_end)


def _write_errno(fd: int):
    try:
        os.write(fd, b"x")
        return "ok"
    except OSError as exc:
        return exc.errno


def zero_byte_write() -> dict:
    read_end, write_end = fresh_pipe()
    try:
        return {"written": os.write(write_end, b""), "error": None}
    except OSError as exc:
        return {"written": None, "error": exc.errno}
    finally:
        _close(read_end)
        os.close(write_end)


def poll_and_select() -> dict:
    """Ask both readiness calls about the same pipe, and unpack each answer correctly.

    ``select`` returns three lists - readable, writable, exceptional - so the writable answer is
    the second one. Reading the first list would report "not writable" for every descriptor.
    """
    read_end, write_end = fresh_pipe()
    try:
        poller = select.poll()
        poller.register(write_end, select.POLLOUT | select.POLLERR)
        before = poller.poll(0)
        writable_before = select.select([], [write_end], [], 0)[1]
        errno_value = _write_errno(write_end)
        after = poller.poll(0)
        writable_after = select.select([], [write_end], [], 0)[1]
        return {
            "poll_before": [events for _, events in before],
            "select_writable_before": bool(writable_before),
            "write_errno": errno_value,
            "poll_after": [events for _, events in after],
            "select_writable_after": bool(writable_after),
        }
    finally:
        _close(read_end)
        os.close(write_end)


def closed_descriptor() -> dict:
    read_end, write_end = fresh_pipe()
    os.close(write_end)
    try:
        return {"errno": _write_errno(write_end)}
    finally:
        _close(read_end)


def socket_send_after_shutdown() -> dict:
    left, right = socket.socketpair()
    try:
        left.shutdown(socket.SHUT_WR)
        return {"first": _send_errno(left), "second": _send_errno(left)}
    finally:
        left.close()
        right.close()


def _send_errno(sock: socket.socket):
    try:
        sock.send(b"x")
        return "ok"
    except OSError as exc:
        return exc.errno


def sendall_partial_count() -> dict:
    """sendall reports nothing about how much it sent; the transport knows."""
    left, right = socket.socketpair()
    right.close()
    try:
        left.sendall(b"x" * 1000)
        return {"raised": None}
    except OSError as exc:
        return {"raised": type(exc).__name__, "errno": exc.errno,
                "message": str(exc)[:60]}
    finally:
        left.close()


def main() -> None:
    arms = []
    for label, function in (
        ("buffered_write_then_flush", buffered_write_then_flush),
        ("buffered_flush_retention", buffered_flush_retention),
        ("text_write_then_flush", text_write_then_flush),
        ("write_is_sticky", write_is_sticky),
        ("zero_byte_write", zero_byte_write),
        ("poll_and_select", poll_and_select),
        ("closed_descriptor", closed_descriptor),
        ("socket_send_after_shutdown", socket_send_after_shutdown),
        ("sendall_to_closed_socket", sendall_partial_count),
    ):
        arms.append(probelib.repeat(label, function, times=1))
    notes = {
        "select_constants": {"POLLIN": select.POLLIN, "POLLOUT": select.POLLOUT,
                             "POLLERR": select.POLLERR, "POLLHUP": select.POLLHUP},
        "python": sys.version.split()[0],
        "runs_per_arm": 1,
        "why_once": "every arm answers with an errno, a mask or a return value; none of them "
                    "moves between runs on this host",
    }
    probelib.save("04_python", probelib.header("04_python", notes, arms))
    for arm in arms:
        print(f"{arm['label']:30s} {arm['runs'][0]}")


if __name__ == "__main__":
    main()
FIN, RST, close and shutdown sandbox/05_sockets.py
"""The socket boundary: FIN, RST, close and shutdown, and where EPIPE appears in the sequence.

Every sequence here is deterministic - the errno of each one-byte send does not move between
runs - so those arms run once. The two cost arms are timing measurements, which do move, so
they keep five runs and a range.
"""
from __future__ import annotations

import socket
import subprocess
import sys
import time

import probelib

ADDR = ("127.0.0.1", 0)
CHILD = '''
import signal, socket, sys
sock = socket.socket()
sock.connect(("127.0.0.1", {port}))
mode = {mode!r}
if mode == "sig_dfl":
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
sock.sendall(b"x" * 1048576)
print("sent", file=sys.stderr)
'''


def pair() -> tuple[socket.socket, socket.socket, socket.socket]:
    listener = socket.socket()
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(ADDR)
    listener.listen(1)
    client = socket.socket()
    client.connect(listener.getsockname())
    server, _ = listener.accept()
    for side in (client, server):
        side.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        side.settimeout(10)
    return listener, client, server


def send_errno(sock: socket.socket):
    try:
        sock.send(b"x")
        return "ok"
    except OSError as exc:
        return exc.errno


def sequence(sock: socket.socket, count: int = 3) -> list:
    return [send_errno(sock) for _ in range(count)]


def peer_close_no_unread() -> dict:
    listener, client, server = pair()
    try:
        server.close()
        time.sleep(0.02)
        outcomes = sequence(client)
        return {"outcomes": outcomes, "last": send_errno(client)}
    finally:
        client.close()
        listener.close()


def peer_close_with_unread() -> dict:
    listener, client, server = pair()
    try:
        client.send(b"x")          # the server never reads this
        server.close()             # close with data outstanding: a reset
        time.sleep(0.02)
        return {"outcomes": sequence(client), "read": _recv(client)}
    finally:
        client.close()
        listener.close()


def shut_wr_local() -> dict:
    listener, client, server = pair()
    try:
        server.shutdown(socket.SHUT_WR)
        return {"outcomes": sequence(server, 2)}
    finally:
        client.close()
        server.close()
        listener.close()


def peer_shut_wr_half_close() -> dict:
    listener, client, server = pair()
    try:
        client.shutdown(socket.SHUT_WR)
        outcomes = sequence(server, 2)
        server.shutdown(socket.SHUT_WR)
        received = 0
        while True:
            piece = client.recv(16)
            if not piece:
                break
            received += len(piece)
        return {"outcomes": outcomes, "client_read": received}
    finally:
        client.close()
        server.close()
        listener.close()


def peer_shut_wr_then_close() -> dict:
    listener, client, server = pair()
    try:
        client.shutdown(socket.SHUT_WR)
        client.close()
        time.sleep(0.02)
        return {"outcomes": sequence(server)}
    finally:
        server.close()
        listener.close()


def epipe_then_recv() -> dict:
    listener, client, server = pair()
    try:
        server.close()
        time.sleep(0.02)
        first = send_errno(client)
        return {"send": first, "recv": _recv(client)}
    finally:
        client.close()
        listener.close()


def _recv(sock: socket.socket):
    try:
        piece = sock.recv(16)
        return "eof" if piece == b"" else piece.decode("latin-1")
    except OSError as exc:
        return exc.errno


def shutdown_twice() -> dict:
    listener, client, server = pair()
    try:
        server.shutdown(socket.SHUT_WR)
        try:
            server.shutdown(socket.SHUT_WR)
            second = "ok"
        except OSError as exc:
            second = exc.errno
        return {"first": "ok", "second": second}
    finally:
        client.close()
        server.close()
        listener.close()


def send_after_close() -> dict:
    listener, client, server = pair()
    try:
        server.close()
        client.close()
        return {"errno": send_errno(client)}
    finally:
        listener.close()


def epipe_cost() -> dict:
    listener, client, server = pair()
    try:
        server.close()
        time.sleep(0.02)
        send_errno(client)
        count = 10000
        started = time.perf_counter_ns()
        seen = {}
        for _ in range(count):
            answer = send_errno(client)
            seen[answer] = seen.get(answer, 0) + 1
        elapsed = time.perf_counter_ns() - started
        return {"calls": count, "ns_per_call": round(elapsed / count, 1),
                "distinct": sorted(str(key) for key in seen)}
    finally:
        client.close()
        listener.close()


def healthy_cost() -> dict:
    listener, client, server = pair()
    try:
        count = 10000
        started = time.perf_counter_ns()
        for _ in range(count):
            client.send(b"x")
        elapsed = time.perf_counter_ns() - started
        total = 0
        while total < count:
            piece = server.recv(65536)
            if not piece:
                break
            total += len(piece)
        return {"calls": count, "received": total,
                "ns_per_call": round(elapsed / count, 1)}
    finally:
        client.close()
        server.close()
        listener.close()


def child_socket(mode: str) -> dict:
    listener = socket.socket()
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(ADDR)
    listener.listen(1)
    port = listener.getsockname()[1]
    process = subprocess.Popen([sys.executable, "-c", CHILD.format(port=port, mode=mode)],
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    conn, _ = listener.accept()
    # The client wrote nothing yet; close with nothing unread so the write meets a FIN,
    # then a reset once data follows.
    conn.close()
    listener.close()
    _, stderr = process.communicate(timeout=30)
    return {"rc": process.returncode,
            "signal": -process.returncode if process.returncode < 0 else None,
            "stderr": stderr.decode("utf-8", "replace").strip()[-200:]}


def main() -> None:
    # An errno, an exit status or a byte count from one sequence is the same on the tenth run;
    # a cost per call is not, so only the cost arms are repeated.
    deterministic = [
        ("peer_close_no_unread", peer_close_no_unread),
        ("peer_close_with_unread", peer_close_with_unread),
        ("shut_wr_local", shut_wr_local),
        ("peer_shut_wr_half_close", peer_shut_wr_half_close),
        ("peer_shut_wr_then_close", peer_shut_wr_then_close),
        ("epipe_then_recv", epipe_then_recv),
        ("shutdown_twice", shutdown_twice),
        ("send_after_close", send_after_close),
        ("child_socket_default", lambda: child_socket("default")),
        ("child_socket_sig_dfl", lambda: child_socket("sig_dfl")),
    ]
    timing = [
        ("epipe_cost", epipe_cost),
        ("healthy_cost", healthy_cost),
    ]
    arms = [probelib.repeat(label, function, times=1) for label, function in deterministic]
    arms += [probelib.repeat(label, function, times=5) for label, function in timing]
    notes = {
        "shape": "TCP over 127.0.0.1; every send is one byte; the sequence is the errno of each "
                 "consecutive send, 20 ms after the peer's action.",
        "address": "loopback IPv4, listener bound to port 0",
        "send_bytes": 1,
        "child_payload": 1048576,
        "runs_per_arm": {"sequence": 1, "cost": 5},
    }
    probelib.save("05_sockets", probelib.header("05_sockets", notes, arms))
    for arm in arms:
        print(f"{arm['label']:28s} {arm['runs'][0]}")


if __name__ == "__main__":
    main()
the pipelines and their statuses sandbox/06_shell.py
"""What a shell reports when the program on the left of a pipe loses its reader.

Every arm here is deterministic - a pipeline's status does not move between runs - so each is
run once. The dash arms exist because the common claim that only bash has ``pipefail`` is worth
checking on the host that prints the table: dash is run with and without the option.
"""
from __future__ import annotations

import pathlib
import re
import subprocess

import probelib

PIPELINES = {
    "seq_head": "seq 1 1000000 | head -n 1",
    "seq_head_pipefail": "set -o pipefail; seq 1 1000000 | head -n 1",
    "yes_head_pipefail": "set -o pipefail; yes | head -n 1",
    "seq_head_zero_bytes": "set -o pipefail; seq 1 1000000 | head -c 0",
    "cat_zero_head": "set -o pipefail; cat /dev/zero | head -c 1",
    "dd_head": "set -o pipefail; dd if=/dev/zero bs=1M count=64 2>/dev/null | head -c 1",
    "grep_m1_pipefail": "set -o pipefail; seq 1 1000000 | grep -m1 5",
    "python_print_head": "python3 -c \"for i in range(1000000): print(i)\" | head -n 1",
    "python_print_head_pipefail":
        "set -o pipefail; python3 -c \"for i in range(1000000): print(i)\" | head -n 1",
    "python_sig_dfl_head_pipefail":
        "set -o pipefail; python3 -c \"import signal; signal.signal(signal.SIGPIPE, "
        "signal.SIG_DFL)\nfor i in range(1000000): print(i)\" | head -n 1",
    "python_small_head_pipefail":
        "set -o pipefail; python3 -c \"print('one line')\" | head -n 1",
    "python_devnull_recipe_loop_head_pipefail":
        "set -o pipefail; python3 -c \"import os, sys\n"
        "try:\n"
        " for i in range(1000000): print(i)\n"
        " sys.stdout.flush()\n"
        "except BrokenPipeError:\n"
        " os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())\n"
        " sys.exit(0)\" | head -n 1",
    "python_devnull_recipe_head_pipefail":
        "set -o pipefail; python3 -c \"import os, sys\n"
        "for i in range(1000000):\n print(i)\n"
        "try:\n sys.stdout.flush()\n"
        "except BrokenPipeError:\n"
        " os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())\n"
        " sys.exit(0)\" | head -n 1",
}

# The dash side: the same seq pipeline without the option, with it, and a pipeline whose first
# command fails, which is the cheapest proof that dash took the option rather than ignoring it.
DASH_PIPELINES = {
    "dash_seq_head": PIPELINES["seq_head"],
    "dash_seq_head_pipefail": PIPELINES["seq_head_pipefail"],
    "dash_python_print_head_pipefail": PIPELINES["python_print_head_pipefail"],
    "dash_false_true_pipefail": "set -o pipefail; false | true",
}

SHELLS = {"bash": "/bin/bash", "dash": "/bin/dash"}


def shell_version(path: str) -> str:
    """bash answers --version on stdout; dash answers that it has no such option."""
    result = subprocess.run([path, "--version"], capture_output=True, text=True)
    return (result.stdout or result.stderr).strip().splitlines()[0]


def bash_version() -> str | None:
    match = re.search(r"version (\d+\.\d+\.\d+)", shell_version(SHELLS["bash"]))
    return match.group(1) if match else None


def dash_reports_version() -> bool:
    """True only if the binary names a version somewhere a shell can ask for it."""
    result = subprocess.run([SHELLS["dash"], "-c", "echo ${DASH_VERSION}"],
                            capture_output=True, text=True)
    return bool(result.stdout.strip())


def package_record(package: str) -> dict:
    """What the image's package database says about a package, if it has one at all."""
    result = subprocess.run(["dpkg-query", "-W", package], capture_output=True, text=True)
    return {
        "package": package,
        "rc": result.returncode,
        "stdout": result.stdout.strip(),
        "stderr": result.stderr.strip(),
        "status_file": pathlib.Path("/var/lib/dpkg/status").is_file(),
    }


def run(shell: str, command: str) -> dict:
    result = subprocess.run([shell, "-c", command], capture_output=True, timeout=60)
    stderr = result.stderr.decode("utf-8", "replace")
    lines = [line for line in stderr.strip().splitlines() if line.strip()]
    return {
        "rc": result.returncode,
        "signal": -result.returncode if result.returncode < 0 else None,
        "stdout_bytes": len(result.stdout),
        "stderr_lines": len(lines),
        "stderr_tail": lines[-2:] if lines else [],
    }


def main() -> None:
    arms = []
    for label, command in PIPELINES.items():
        arms.append(probelib.repeat(label,
                                    lambda command=command: run("/bin/bash", command), times=1))
    for label, command in DASH_PIPELINES.items():
        arms.append(probelib.repeat(label,
                                    lambda command=command: run("/bin/dash", command), times=1))
    notes = {
        "shells": {name: shell_version(path) for name, path in SHELLS.items()},
        "bash_version": bash_version(),
        "dash_version": None,
        "dash_version_note": "neither question answers: dash --version says 'Illegal option', "
                             "DASH_VERSION is empty, and dpkg-query -W dash finds no package "
                             "record in this image, so the only evidence kept here is what "
                             "the option does (dash_false_true_pipefail)",
        "dash_version_reported": dash_reports_version(),
        "dash_package": package_record("dash"),
        "dash_pipefail_supported": any(
            arm["label"] == "dash_false_true_pipefail" and arm["runs"][0]["rc"] == 1
            for arm in arms),
        "pipelines": {**PIPELINES, **DASH_PIPELINES},
        "bash_wait_status": "128 plus the signal number for a process killed by a signal",
        "runs_per_arm": 1,
    }
    probelib.save("06_shell", probelib.header("06_shell", notes, arms))
    print("dash package record:", notes["dash_package"])
    for arm in arms:
        run_record = arm["runs"][0]
        tail = run_record["stderr_tail"][-1][:90] if run_record["stderr_tail"] else ""
        print(f"{arm['label']:42s} rc={run_record['rc']:>4} "
              f"out={run_record['stdout_bytes']:>8} stderr={tail!r}")


if __name__ == "__main__":
    main()
what each outcome costs sandbox/07_cost.py
"""What each outcome costs: a write that is delivered, a write that raises, and a discard."""
from __future__ import annotations

import os
import threading
import time

import probelib

MB64 = 65536


def _drain(read_end: int, stop: threading.Event, counter: list[int]) -> None:
    while not stop.is_set():
        try:
            piece = os.read(read_end, 262144)
        except OSError:
            return
        if not piece:
            return
        counter[0] += len(piece)


def live_writes(count: int, payload: bytes) -> dict:
    read_end, write_end = os.pipe()
    stop = threading.Event()
    counter = [0]
    reader = threading.Thread(target=_drain, args=(read_end, stop, counter), daemon=True)
    reader.start()
    started = time.perf_counter_ns()
    for _ in range(count):
        os.write(write_end, payload)
    elapsed = time.perf_counter_ns() - started
    stop.set()
    os.close(write_end)
    reader.join(timeout=5)
    os.close(read_end)
    return {"calls": count, "bytes": count * len(payload),
            "ns_per_call": round(elapsed / count, 1), "drained": counter[0]}


def broken_writes(count: int) -> dict:
    read_end, write_end = os.pipe()
    os.close(read_end)
    started = time.perf_counter_ns()
    caught = 0
    try:
        for _ in range(count):
            try:
                os.write(write_end, b"x")
            except BrokenPipeError:
                caught += 1
    finally:
        elapsed = time.perf_counter_ns() - started
        os.close(write_end)
    return {"calls": count, "caught": caught, "ns_per_call": round(elapsed / count, 1)}


def devnull_writes(count: int, payload: bytes) -> dict:
    fd = os.open(os.devnull, os.O_WRONLY)
    try:
        started = time.perf_counter_ns()
        for _ in range(count):
            os.write(fd, payload)
        elapsed = time.perf_counter_ns() - started
    finally:
        os.close(fd)
    return {"calls": count, "bytes": count * len(payload),
            "ns_per_call": round(elapsed / count, 1)}


def main() -> None:
    arms = [
        probelib.repeat("write_one_byte_live", lambda: live_writes(200000, b"x")),
        probelib.repeat("write_64k_live", lambda: live_writes(4000, b"x" * MB64)),
        probelib.repeat("write_one_byte_broken", lambda: broken_writes(200000)),
        probelib.repeat("write_64k_devnull", lambda: devnull_writes(4000, b"x" * MB64)),
    ]
    notes = {
        "clock": "perf_counter_ns around the loop in this process; the reader runs in a thread "
                 "of the same process for the live arms",
        "calls_per_arm": {"one_byte": 200000, "64k": 4000},
    }
    probelib.save("07_cost", probelib.header("07_cost", notes, arms))
    for arm in arms:
        print(f"{arm['label']:26s} "
              f"{[run['ns_per_call'] for run in arm['runs']]}")


if __name__ == "__main__":
    main()
the response writer and the client that left sandbox/08_repro.py
"""A response writer and a client that reads one kilobyte: how much of 64 MiB is accepted."""
from __future__ import annotations

import json
import os
import socket
import subprocess
import sys

import probelib

HERE = probelib.HERE

SERVER = '''
import json, os, signal, socket, sys
port = int(sys.argv[1])
mode = sys.argv[2]
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", port))
server.listen(1)
conn, _ = server.accept()
conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if mode == "sig_dfl":
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
total = 0
first = second = None
first_kind = second_kind = None
try:
    while total < 64 * 1024 * 1024:
        total += conn.send(b"x" * 65536)
except OSError as exc:
    first = exc.errno
    first_kind = type(exc).__name__
    try:
        total += conn.send(b"x")
    except OSError as again:
        second = again.errno
        second_kind = type(again).__name__
answer = {"bytes": total, "errno": first, "kind": first_kind,
          "second_errno": second, "second_kind": second_kind}
if mode == "handled":
    from pipeguard.errors import explain
    detail = explain(OSError(answer["errno"], os.strerror(answer["errno"]))) \\
        if answer["errno"] else None
    answer["reason"] = detail.reason if detail else None
print(json.dumps(answer), file=sys.stderr)
'''


def run(mode: str, read_bytes: int = 1024) -> dict:
    listener = socket.socket()
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(("127.0.0.1", 0))
    port = listener.getsockname()[1]
    listener.close()
    process = subprocess.Popen([sys.executable, "-c", SERVER, str(port), mode],
                               stderr=subprocess.PIPE, stdout=subprocess.DEVNULL,
                               env={**os.environ, "PYTHONPATH": str(HERE.parent)})
    client = socket.socket()
    for _ in range(100):
        try:
            client.connect(("127.0.0.1", port))
            break
        except ConnectionRefusedError:
            import time
            time.sleep(0.02)
    client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    received = b""
    while len(received) < read_bytes:
        piece = client.recv(read_bytes - len(received))
        if not piece:
            break
        received += piece
    client.close()
    _, stderr = process.communicate(timeout=60)
    lines = stderr.decode("utf-8", "replace").strip().splitlines()
    answer = {}
    for line in lines:
        if line.startswith("{"):
            answer = json.loads(line)
    return {
        "mode": mode,
        "rc": process.returncode,
        "signal": -process.returncode if process.returncode < 0 else None,
        "client_read": len(received),
        "accepted": answer.get("bytes"),
        "errno": answer.get("errno"),
        "second_errno": answer.get("second_errno"),
        "second_kind": answer.get("second_kind"),
        "kind": answer.get("kind"),
        "reason": answer.get("reason"),
        "traceback": any("Traceback" in line for line in lines),
        "stderr_tail": lines[-1:] if lines else [],
    }


def main() -> None:
    arms = [probelib.repeat(mode, lambda mode=mode: run(mode))
            for mode in ("default", "sig_dfl", "handled")]
    arms.append(probelib.repeat("default_client_reads_64k",
                                lambda: run("default", read_bytes=65536)))
    notes = {
        "shape": "TCP loopback; the server writes 64 MiB in 64 KiB sends; the client reads "
                 "N bytes and closes; the server records the bytes conn.send() accepted.",
        "payload": 64 * 1024 * 1024,
        "send_chunk": 65536,
        "default_read": 1024,
    }
    probelib.save("08_repro", probelib.header("08_repro", notes, arms))
    for arm in arms:
        first = arm["runs"][0]
        print(f"{arm['label']:26s} accepted={[run['accepted'] for run in arm['runs']]} "
              f"rc={first['rc']} errno={first['errno']}->{first['second_errno']} "
              f"traceback={first['traceback']} reason={first.get('reason')}")


if __name__ == "__main__":
    main()
the tree’s own counts sandbox/09_counts.py
"""The tree's own counts: files, lines, and the suite's result, measured rather than declared."""
from __future__ import annotations

import pathlib
import re
import subprocess
import sys

import probelib

HERE = probelib.HERE.parent
PACKAGE = HERE / "pipeguard"
TESTS = PACKAGE / "tests"
SANDBOX = HERE / "sandbox"
EXAMPLES = HERE / "examples"


def lines(path: pathlib.Path) -> int:
    return len(path.read_text(encoding="utf-8").splitlines())


def main() -> None:
    package_files = sorted(PACKAGE.glob("*.py"))
    test_files = sorted(TESTS.glob("*.py"))
    probes = sorted(path for path in SANDBOX.glob("*.py"))
    examples = sorted(EXAMPLES.glob("*.py"))
    result = subprocess.run([sys.executable, "-m", "pytest", "pipeguard/tests", "-q",
                             "-p", "no:warnings", "-p", "no:asyncio", "-p", "no:cacheprovider"],
                            cwd=str(HERE), capture_output=True, text=True)
    summary = [line for line in result.stdout.splitlines() if "passed" in line]
    passed = int(re.search(r"(\d+) passed", summary[-1]).group(1)) if summary else 0
    notes = {
        "pytest_passed": passed,
        "pytest_rc": result.returncode,
        "pytest_summary": summary[-1] if summary else "",
        "package_files": len(package_files),
        "package_lines": sum(lines(path) for path in package_files),
        "test_files": len(test_files),
        "test_lines": sum(lines(path) for path in test_files),
        "probe_files": len(probes),
        "probe_lines": sum(lines(path) for path in probes),
        "example_files": len(examples),
        "example_lines": sum(lines(path) for path in examples),
        "package_names": [path.name for path in package_files],
        "test_names": [path.name for path in test_files],
        "probe_names": [path.name for path in probes],
    }
    arms = [{"label": "the_tree", "runs": [notes]}]
    probelib.save("09_counts", probelib.header("09_counts", notes, arms))
    for key, value in notes.items():
        print(f"{key}: {value}")
    if result.returncode != 0:
        print(result.stdout[-800:])
        raise SystemExit("the suite did not pass")


if __name__ == "__main__":
    main()
the package on the three named situations sandbox/11_package.py
"""The package on the three situations the page names, plus one errno it does not, once.

Every answer here is an errno, a byte count or an exit status, and those do not move between
runs, so one call per arm is enough to record what the package answers.
"""
from __future__ import annotations

import errno
import fcntl
import json
import os
import socket
import subprocess
import sys
import time

import probelib

HERE = probelib.HERE
LINUX = sys.platform == "linux"
F_SETPIPE_SZ = getattr(fcntl, "F_SETPIPE_SZ", 1031)

TOOL = '''
import os, sys
from pipeguard.stdio import guarded
with guarded(sys.stdout):
    sys.stdout.write("x" * 1000)
    sys.stdout.flush()
'''

FATAL = '''
import os
from pipeguard.signals import die_on_sigpipe
with die_on_sigpipe():
    os.write(1, b"x")
'''

EXIT_CLEAN = '''
import sys
from pipeguard.stdio import exit_cleanly
sys.stdout.write("x" * 1000)
exit_cleanly(sys.stdout, code=0)
'''


def run_tool(code: str) -> dict:
    read_end, write_end = os.pipe()
    os.close(read_end)
    try:
        result = subprocess.run([sys.executable, "-c", code], stdout=write_end,
                                stderr=subprocess.PIPE,
                                env={**os.environ, "PYTHONPATH": str(HERE.parent)})
    finally:
        os.close(write_end)
    stderr = result.stderr.decode("utf-8", "replace")
    return {"rc": result.returncode, "stderr_tail": stderr.strip().splitlines()[-1:] if stderr else [],
            "ignored_exception": "Exception ignored" in stderr}


def write_all_no_reader() -> dict:
    from pipeguard.sink import PipeClosed, write_all
    read_end, write_end = os.pipe()
    os.close(read_end)
    try:
        try:
            return {"written": write_all(write_end, b"x" * (4 * 1048576)), "raised": None}
        except PipeClosed as exc:
            return {"written": exc.written, "raised": "PipeClosed", "errno": exc.errno}
    finally:
        os.close(write_end)


def write_all_with_reader(read_bytes: int) -> dict:
    """A reader that takes N bytes, holds the pipe for 50 ms, then leaves."""
    from pipeguard.sink import PipeClosed, write_all
    read_end, write_end = os.pipe()
    fcntl.fcntl(write_end, F_SETPIPE_SZ, 1048576)
    process = os.fork()
    if process == 0:
        os.close(write_end)
        try:
            if read_bytes:
                os.read(read_end, read_bytes)
            time.sleep(0.05)
        finally:
            os.close(read_end)
            os._exit(0)
    os.close(read_end)
    try:
        try:
            written = write_all(write_end, b"x" * (4 * 1048576))
            return {"written": written, "raised": None}
        except PipeClosed as exc:
            return {"written": exc.written, "raised": "PipeClosed"}
    finally:
        os.close(write_end)
        os.waitpid(process, 0)


def explain_matrix() -> dict:
    from pipeguard.errors import explain
    return {str(number): explain(OSError(number, os.strerror(number))).reason
            for number in (errno.EPIPE, errno.ECONNRESET, errno.EBADF, errno.EAGAIN)}


def send_matrix() -> dict:
    from pipeguard.sockets import send_or_closed
    left, right = socket.socketpair()
    try:
        right.shutdown(socket.SHUT_WR)
        half = send_or_closed(left, b"ab")
    finally:
        left.close()
        right.close()
    first, second = socket.socketpair()
    second.close()
    try:
        sent, closed = send_or_closed(first, b"x")
        if not closed:
            sent, closed = send_or_closed(first, b"x")
    finally:
        first.close()
    return {"half_closed": list(half), "closed": [sent, closed]}


def main() -> None:
    if not LINUX:
        raise SystemExit("11_package raises the pipe size with F_SETPIPE_SZ, which only Linux "
                         "provides")
    plan = [
        ("write_all_no_reader", write_all_no_reader),
        ("write_all_reader_never_reads", lambda: write_all_with_reader(0)),
        ("write_all_reader_takes_one_byte", lambda: write_all_with_reader(1)),
        ("guarded_tool", lambda: run_tool(TOOL)),
        ("fatal_on_sigpipe", lambda: run_tool(FATAL)),
        ("exit_cleanly_zero", lambda: run_tool(EXIT_CLEAN)),
        ("explain_matrix", explain_matrix),
        ("send_matrix", send_matrix),
    ]
    arms = [probelib.repeat(label, function, times=1) for label, function in plan]
    notes = {
        "shape": "each arm calls the package as a service would; the tool arms give the process "
                 "a stdout pipe whose reader is already gone",
        "pipe_size": 1048576,
        "runs_per_arm": 1,
    }
    probelib.save("11_package", probelib.header("11_package", notes, arms))
    for arm in arms:
        print(f"{arm['label']:32s} {json.dumps(arm['runs'][0])[:150]}")


if __name__ == "__main__":
    main()
the six checks in one run examples/broken_pipe_demo.py
"""Six checks in one run: the disposition, the count, the sentence, and the two socket answers."""
import io
import os
import socket

from pipeguard import (PipeClosed, explain, guarded, send_or_closed, sigpipe_disposition,
                       write_all)


def main() -> None:
    print(f"disposition: {sigpipe_disposition()}")

    read_end, write_end = os.pipe()
    os.close(read_end)
    try:
        write_all(write_end, b"x" * 4096)
    except PipeClosed as exc:
        print(f"write_all to a closed reader: {exc.written} bytes, {type(exc).__name__} "
              f"(errno {exc.errno})")
    finally:
        os.close(write_end)

    answer = explain(OSError(32, os.strerror(32)))
    print(f"explain: {answer.reason} - {answer.hint.split(':')[0]}")

    left, right = socket.socketpair()
    try:
        right.shutdown(socket.SHUT_WR)
        sent, closed = send_or_closed(left, b"ab")
        print(f"half-closed peer: {sent} bytes sent, closed={closed}")
    finally:
        left.close()
        right.close()

    first, second = socket.socketpair()
    second.close()
    try:
        sent, closed = (0, False)
        for _ in range(4):
            sent, closed = send_or_closed(first, b"x" * 4096)
            if closed:
                break
        print(f"closed peer: {sent} bytes sent, closed={closed}")
    finally:
        first.close()

    read_end, write_end = os.pipe()
    os.close(read_end)
    stream = io.open(write_end, "wb", buffering=1024)
    with guarded(stream):
        stream.write(b"x" * 100)
        stream.flush()
    print("guarded: BrokenPipeError contained, exit 0")

    print("done: 6 checks")


if __name__ == "__main__":
    main()

Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.