Store data exports, file verification, and report generation often rely on Python to run external programs. If a task on a dedicated server shows as “running” while the CPU is mostly idle and the logs stop growing, check the output pipes first. The child process may be waiting for standard error to be read while the parent waits for standard output to end. Adding memory or restarting the task will not fix that chain of waits.
The experiments below run under a regular user account on Debian 12 or Ubuntu Server 24.04 LTS with Python 3 installed. Connection credentials for an Evpn dedicated server are available in the console after payment; Linux access is via SSH. These experiments do not modify networking, system services, or business files.
1. Establish what is waiting before blaming the hardware
stdout=PIPE and stderr=PIPE create two kernel pipes with limited capacity. Reading stdout to completion before reading stderr may look straightforward, but it can deadlock: the child fills stderr and cannot continue, so it cannot close stdout either. The parent keeps waiting for end-of-file on stdout.
Calling wait() before reading either stream is another unsafe pattern. If the child fills either pipe before it exits, the wait cannot finish. Pipe capacity is not an application contract, and a test that produces little log output is no guarantee of safety.
When investigating, record the PID, PGID, state, and elapsed time of the parent, its direct child, and any descendants. Then check whether their standard output points to a pipe:
ps -eo pid,ppid,pgid,stat,etime,args --forest
For a verified PID, inspect the link targets of /proc/PID/fd/1 and /proc/PID/fd/2. A target such as pipe:[…] is a clue, not proof of a fault on its own. It must be considered alongside the program’s read order and the controlled reproduction below.
Exit status, end of output, and task success are three separate conditions. Descendants may still hold a pipe’s write end after the direct child exits. Finishing output collection does not prove that the business result is complete.
2. Build a repeatable fixture with bounded output
Save the following as pipe_fixture.py. It writes a finite amount of data to stderr, prints a readiness marker, and then starts a descendant that inherits the standard streams. The output volume and sleep durations are experimental parameters, not business workload metrics.
import subprocess
import sys
import time
sys.stderr.write("E" * (256 * 1024))
sys.stderr.flush()
print("fixture-ready", flush=True)
subprocess.Popen([
sys.executable,
"-c",
"import time; time.sleep(60)",
])
time.sleep(60)
Do not dump large volumes of output into production logs. For verification, retain only the byte counts, readiness marker, and exit status. The fixture does not read credentials, access external addresses, or create business data.
If you need to verify an incorrect read order, use a separate test terminal and arrange an external timeout safeguard in advance. For the actual collector, use the dual-stream approach in the next section directly. There is no need to create an unmanaged, indefinite wait on a production server.
3. Drain both streams and arrange cleanup on timeout
Save the collector below as collect_fixture.py in the same directory. communicate() handles both streams concurrently. start_new_session=True creates a separate session for the fixture, whose initial process group ID equals the direct child’s PID.
import os
import signal
import subprocess
import sys
p = subprocess.Popen(
[sys.executable, "pipe_fixture.py"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=True,
)
def signal_group(sig):
try:
os.killpg(p.pid, sig)
except ProcessLookupError:
pass
timed_out = False
forced = False
try:
out, err = p.communicate(timeout=3)
except subprocess.TimeoutExpired:
timed_out = True
signal_group(signal.SIGTERM)
try:
out, err = p.communicate(timeout=2)
except subprocess.TimeoutExpired:
forced = True
signal_group(signal.SIGKILL)
out, err = p.communicate()
print({
"pid": p.pid,
"pgid": p.pid,
"timed_out": timed_out,
"forced": forced,
"returncode": p.returncode,
"stdout_bytes": len(out),
"stderr_bytes": len(err),
"ready": b"fixture-ready\n" in out,
})
Run python3 collect_fixture.py in the terminal. The expected result includes the readiness marker and 262144 bytes on stderr, with execution entering the timeout branch because the fixture remains asleep. On POSIX systems, Python uses a negative return code to indicate that the direct child was terminated by a signal.
Do not concatenate the partial output attached to the timeout exception with the result of the second communicate() call; doing so may count output twice. Calling the method again after sending the termination signal completes output collection and reaps the direct child. It does not rerun the task.
4. Test failure paths to verify that cleanup works
One successful completion does not establish that timeout handling is reliable. Keep the original fixture, make test copies, and change only one condition at a time.
For the first test, remove the descendant launch and the final sleep. Confirm that the collector completes normally, timed_out is false, and the return code is zero. For the second test, use the original fixture and confirm that the timeout is recorded separately rather than misreported as “empty output.”
For the third test, add these two lines before the fixture writes any output so that the direct child ignores graceful termination:
import signal
signal.signal(signal.SIGTERM, signal.SIG_IGN)
This should trigger the forced-termination branch. Then use the PGID reported by the collector to check the process list for surviving group members. Before making the query, verify the command line and process identity so that a reused identifier is not mistaken for the original task.
Test a nonzero exit as well: change the end of the normally completing version to sys.exit(7) and confirm that the application wrapper preserves that status. A readiness marker in the output is not a reason to pass a failed result downstream.
The process-group approach is suitable only for controlled tasks that do not deliberately escape the group. A descendant that creates its own session may leave the original group. For such programs, use a service manager’s control-group lifecycle management; do not claim that one killpg() call can clean up every descendant.
5. Turn the findings into a batch execution contract
communicate() buffers output in memory, so the implementation above is suitable only for tasks with a defined output limit. Long-running exports and debug logs need concurrent reading of both streams or separate redirection to managed files. Set disk budgets, retention policies, and termination rules for excessive output at the same time. Do not turn a blocked pipe into memory or disk exhaustion.
Pass arguments as a list, and explicitly define the executable, working directory, and allowed environment variables. Do not enable a shell just to assemble filenames, and do not put access tokens in command lines or exception output. When decoding text, specify the encoding and error-handling policy; keep binary results as bytes.
The final verification record should include at least the task identifier, start and end times, whether a timeout occurred, whether forced termination was needed, the direct child’s return code, byte counts for both streams, and validation results for the business artifacts. Calculate elapsed time with a monotonic clock; use calendar timestamps in logs only to correlate events.
The acceptance criterion is not “the script finally returned.” The normal, failure, and timeout paths must all produce explicit outcomes, no controlled descendants should remain, and failed artifacts must not enter the success workflow. That turns an intermittent hang into a task execution contract that can be reproduced, diagnosed, and verified.
Frequently asked questions
Is it safe to call wait() before reading output?
Not when stdout or stderr uses a pipe that can fill. The child can wait for a reader while the parent waits for the child to exit. Use communicate() for bounded output, or bounded streaming collection for large output.
Does a communicate() timeout terminate all descendants?
No. On Linux, start the controlled job in a separate session, signal its process group with SIGTERM and then SIGKILL if necessary, and collect output and the direct child's status. Descendants that leave the group are outside this guarantee.
AMD EPYC 7543P Dedicated Server
From $457.5/month