GPT on Question 14, Sep 13
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?Use an EXIT/signal trap, record child PIDs, terminate them, then wait to reap them:
#!/usr/bin/env bash
set -Eeuo pipefail
children=()
cleanup() {
trap - EXIT INT TERM HUP
((${#children[@]})) || return
kill -TERM "${children[@]}" 2>/dev/null || true
sleep 1
kill -KILL "${children[@]}" 2>/dev/null || true
wait "${children[@]}" 2>/dev/null || true
}
trap cleanup EXIT INT TERM HUP
worker_a &
children+=("$!")
worker_b &
children+=("$!")
waitImportant caveats:
- •This handles direct children and trappable exits/signals.
- •Nothing in Bash can run cleanup if the parent receives
SIGKILL, crashes, or the machine loses power. - •If children create their own descendants, PID tracking is insufficient. Run the workload in a dedicated process group/cgroup and terminate that group, preferably using a supervisor such as
systemd, Docker, or another service manager. - •Avoid the common
trap 'kill 0' EXITpattern unless you fully control the process group—it can kill the invoking shell or unrelated processes.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-13 09:05:24 UTC
- Run
- 20260913T090021Z-a7390a
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,059 characters · 784 tokens out incl. hidden reasoning · 16.2 s
Use an `EXIT`/signal trap, record child PIDs, terminate them, then `wait` to reap them:
```bash
#!/usr/bin/env bash
set -Eeuo pipefail
children=()
cleanup() {
trap - EXIT INT TERM HUP
((${#children[@]})) || return
kill -TERM "${children[@]}" 2>/dev/null || true
sleep 1
kill -KILL "${children[@]}" 2>/dev/null || true
wait "${children[@]}" 2>/dev/null || true
}
trap cleanup EXIT INT TERM HUP
worker_a &
children+=("$!")
worker_b &
children+=("$!")
wait
```
Important caveats:
- This handles direct children and trappable exits/signals.
- Nothing in Bash can run cleanup if the parent receives `SIGKILL`, crashes, or the machine loses power.
- If children create their own descendants, PID tracking is insufficient. Run the workload in a dedicated process group/cgroup and terminate that group, preferably using a supervisor such as `systemd`, Docker, or another service manager.
- Avoid the common `trap 'kill 0' EXIT` pattern unless you fully control the process group—it can kill the invoking shell or unrelated processes.
End of response · 35 lines · 1,059 characters · sha256 cdf9e0ff0d0e65445643e7079e7c9d5827230b3aabe41b107b5ba5130f9dddbf