GPT on Question 14, Sep 14
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?For children started directly by the Bash script, use an EXIT trap and terminate the shell’s active jobs:
#!/usr/bin/env bash
cleanup() {
rc=$?
trap - EXIT HUP INT TERM
pids=()
while IFS= read -r pid; do
pids+=("$pid")
done < <(jobs -p)
if ((${#pids[@]})); then
kill -TERM "${pids[@]}" 2>/dev/null || :
wait "${pids[@]}" 2>/dev/null || :
fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
worker_a &
worker_b &
waitImportant limitations:
- •This handles normal exit and catchable signals, but not
SIGKILL, a kernel crash, or power loss. - •It only reliably targets direct children. If workers create descendants, use a dedicated process group/session or, preferably on Linux, a systemd service/cgroup with
KillMode=control-group. - •Avoid a bare
kill 0unless the script is guaranteed to own its process group; otherwise it may kill the invoking shell or unrelated processes. - •For a child that must die immediately when its parent disappears, Linux’s
prctl(PR_SET_PDEATHSIG, ...)is the appropriate mechanism, usually via a small wrapper since Bash has no builtin for it.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-14 09:06:41 UTC
- Run
- 20260914T090022Z-e98262
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,210 characters · 2,395 tokens out incl. hidden reasoning · 34.8 s
For children started directly by the Bash script, use an `EXIT` trap and terminate the shell’s active jobs:
```bash
#!/usr/bin/env bash
cleanup() {
rc=$?
trap - EXIT HUP INT TERM
pids=()
while IFS= read -r pid; do
pids+=("$pid")
done < <(jobs -p)
if ((${#pids[@]})); then
kill -TERM "${pids[@]}" 2>/dev/null || :
wait "${pids[@]}" 2>/dev/null || :
fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
worker_a &
worker_b &
wait
```
Important limitations:
- This handles normal exit and catchable signals, but **not `SIGKILL`**, a kernel crash, or power loss.
- It only reliably targets direct children. If workers create descendants, use a dedicated process group/session or, preferably on Linux, a **systemd service/cgroup** with `KillMode=control-group`.
- Avoid a bare `kill 0` unless the script is guaranteed to own its process group; otherwise it may kill the invoking shell or unrelated processes.
- For a child that must die immediately when its parent disappears, Linux’s `prctl(PR_SET_PDEATHSIG, ...)` is the appropriate mechanism, usually via a small wrapper since Bash has no builtin for it.
End of response · 39 lines · 1,210 characters · sha256 ca26584ebf0567d27e93c01d35dbd88a697f49da38379c6e517cdbfadb826415