Sub topic 14
Avoiding pipe buffer deadlocks
This chapter assumes you can use subprocess.run and Popen with stdout=subprocess.PIPE, and that you know what standard input, output and error are. It explains why a child process can freeze while your program waits for it, and how to prevent that.
Why a pipe can fill up
When you pass stdout=subprocess.PIPE, the operating system creates a pipe between the child and your program. A pipe is a fixed-size buffer in the kernel. On Linux the default is 64 KiB. On macOS and Windows it is often smaller. The child writes into one end and your program reads from the other.
The two ends behave like this:
- If the buffer is empty, a read blocks until data arrives or the child closes its end.
- If the buffer is full, the child's write blocks until your program reads some data.
A deadlock happens when your program waits for the child to exit while the child waits for your program to read. Neither can continue, and the program hangs with no error.
Reproducing the problem safely
The following program creates the deadlock but uses a timeout so it ends. The child writes about 1 MB, which is larger than any common pipe buffer. The parent calls wait() and never reads.
import subprocess
import sys
child = "import sys; sys.stdout.write('x' * 1_000_000)"
proc = subprocess.Popen([sys.executable, "-c", child], stdout=subprocess.PIPE)
try:
proc.wait(timeout=2)
print("finished")
except subprocess.TimeoutExpired:
print("deadlock: the child is blocked writing to a full pipe")
proc.kill()
proc.communicate()The output is deadlock: the child is blocked writing to a full pipe. Without the timeout, the program would hang forever. The final communicate() call collects the killed child and closes the pipe.
The Popen documentation warns about this: do not use wait() with stdout=PIPE or stderr=PIPE.
Fix 1: use communicate
communicate() reads all output until the child closes its streams, then waits for the child to exit. It reads while the child runs, so the buffer never stays full.
import subprocess
import sys
child = "import sys; sys.stdout.write('x' * 1_000_000)"
proc = subprocess.Popen([sys.executable, "-c", child], stdout=subprocess.PIPE)
out, _ = proc.communicate()
print(len(out), proc.returncode)The output is 1000000 0. subprocess.run(..., capture_output=True) calls communicate() internally, so it is also safe.
communicate() keeps everything in memory. If the child could produce gigabytes, use one of the other fixes below.
Fix 2: read both streams without blocking on one
Using two pipes creates a second form of the problem. Suppose you read all of proc.stdout and only then read proc.stderr. If the child fills the stderr pipe first, it blocks on stderr while you block on stdout.
You have three safe options:
- Call
communicate(), which handles both pipes. - Merge the streams with
stderr=subprocess.STDOUTand read a single pipe. - Avoid pipes for the stream you do not need to read in your program.
This example merges the streams and reads line by line. The child writes 50,000 lines to each stream.
import subprocess
import sys
child = (
"import sys\n"
"for i in range(50000):\n"
" print('out', i)\n"
" print('err', i, file=sys.stderr)\n"
)
count = 0
with subprocess.Popen(
[sys.executable, "-c", child],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
) as proc:
for line in proc.stdout:
count += 1
print(count, proc.returncode)The output is 100000 0. The cost of merging is that you can no longer tell which line came from which stream.
If you need the streams separate and the output is large, redirect them to files. The child writes to the files directly, so no pipe can fill up.
import subprocess
import sys
import tempfile
child = (
"import sys\n"
"sys.stdout.write('x' * 1_000_000)\n"
"sys.stderr.write('y' * 1_000_000)\n"
)
with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:
subprocess.run([sys.executable, "-c", child], stdout=out, stderr=err, check=True)
print(out.seek(0, 2), err.seek(0, 2))The output is 1000000 1000000. seek(0, 2) moves to the end of each file and returns its size.
If you do not need a stream at all, pass subprocess.DEVNULL. Never set stdout=PIPE and then ignore the pipe.
Fix 3: do not write and read in the wrong order
Deadlocks can also involve standard input. Suppose you write a large amount of data to proc.stdin, and the child echoes it to its stdout as it goes. The child's stdout pipe fills and the child stops reading. Your write then blocks because the child's stdin pipe is full.
The fix is again communicate(input=...), which writes and reads together:
import subprocess
import sys
data = "line\n" * 200_000
child = "import sys\nfor line in sys.stdin:\n sys.stdout.write(line)\n"
result = subprocess.run(
[sys.executable, "-c", child],
input=data,
capture_output=True,
text=True,
check=True,
)
print(result.stdout == data)The output is True. Do not write to proc.stdin yourself and read proc.stdout afterwards when both sides move large amounts of data.
Edge cases
Timeouts and cleanup
communicate(timeout=...) raises TimeoutExpired but does not kill the child. After catching the exception, kill the child and call communicate() again to collect the remaining output and reap the process.
import subprocess
import sys
proc = subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(10)"],
stdout=subprocess.PIPE,
)
try:
out, _ = proc.communicate(timeout=1)
except subprocess.TimeoutExpired:
proc.kill()
out, _ = proc.communicate()
print("killed, exit code", proc.returncode)On Linux and macOS, the exit code is -9, the negative signal number. On Windows, it is 1. subprocess.run(timeout=...) does this cleanup for you.
Grandchildren that keep the pipe open
communicate() returns when every holder of the write end has closed it, not only when your child exits. If the child starts a background process that inherits the pipe, communicate() keeps waiting. Use a timeout, or redirect the background process's output.
Pipelines
In a two-process pipeline, the parent still holds a copy of the first process's stdout. Call producer.stdout.close() after starting the consumer. Then the consumer sees end of input when the producer exits, and the producer receives a broken-pipe error if the consumer dies early.
Reading line by line is not the same as safe
Iterating over proc.stdout is safe because it drains the pipe. It is only safe for the one pipe you read. If you also set stderr=PIPE, that second pipe can still fill up. Merge it, redirect it, or use threads to read both.
Choosing an approach
| Situation | Approach |
|---|---|
| Output is small enough for memory | `run(capture_output=True)` or `communicate()` |
| You need to react to lines as they arrive | `Popen` with `stderr=STDOUT` and iterate `proc.stdout` |
| Large output, streams kept separate | Redirect to files |
| You do not need the output | `DEVNULL` |
| Large input and large output | `communicate(input=...)` |
| Separate streams and live reading | One reader thread per pipe |
Exercise
A program starts a child with stdout=PIPE, stderr=PIPE, then runs out = proc.stdout.read() followed by err = proc.stderr.read(). The child writes 1 MB to stderr first and then a short message to stdout. Why does the program hang, and how do you fix it?
Show answer
The child blocks writing to stderr once that pipe's buffer is full, so it never reaches the stdout write or exits. The parent blocks in proc.stdout.read() waiting for the child to close stdout, so neither side can continue. Fix it with out, err = proc.communicate(), which reads both pipes as data arrives. Alternatively, use stderr=subprocess.STDOUT and read one pipe, or redirect stderr to a file.
Exercise
Why is proc.wait() a risk after Popen(..., stdout=PIPE), and what do you call instead?
Show answer
wait() does not read the pipe. If the child writes more than the pipe buffer holds, it blocks and never exits, so wait() never returns. Call communicate(), which reads the output and then waits for exit. If you must use wait(), send the output to a file or DEVNULL instead of a pipe.