GPT on Question 14, Sep 11
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?The usual Bash pattern is to trap shell exit/signals and terminate any background jobs:
#!/usr/bin/env bash
set -uo pipefail
cleanup() {
rc=$?
trap - EXIT HUP INT TERM # prevent recursive traps
mapfile -t children < <(jobs -pr)
if ((${#children[@]})); then
kill -TERM "${children[@]}" 2>/dev/null || :
wait "${children[@]}" 2>/dev/null || :
fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
worker_one &
worker_two &
waitImportant limitations:
- •Traps do not run if the script gets
SIGKILL, the machine crashes, etc. - •This handles Bash’s direct background jobs, not necessarily grandchildren or daemonized processes.
- •Avoid
kill 0unless the script owns its process group; otherwise it may kill the invoking shell or unrelated processes.
For an entire descendant tree, use a supervisor/cgroup—e.g. run the script as a systemd service with the default KillMode=control-group. On Linux, another option is launching children through a wrapper that sets PR_SET_PDEATHSIG, though that only directly ties each process to its immediate parent.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-11 09:08:30 UTC
- Run
- 20260911T090002Z-da0dd3
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,156 characters · 2,081 tokens out incl. hidden reasoning · 119.3 s
The usual Bash pattern is to trap shell exit/signals and terminate any background jobs:
```bash
#!/usr/bin/env bash
set -uo pipefail
cleanup() {
rc=$?
trap - EXIT HUP INT TERM # prevent recursive traps
mapfile -t children < <(jobs -pr)
if ((${#children[@]})); then
kill -TERM "${children[@]}" 2>/dev/null || :
wait "${children[@]}" 2>/dev/null || :
fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
worker_one &
worker_two &
wait
```
Important limitations:
- Traps do not run if the script gets `SIGKILL`, the machine crashes, etc.
- This handles Bash’s direct background jobs, not necessarily grandchildren or daemonized processes.
- Avoid `kill 0` unless the script owns its process group; otherwise it may kill the invoking shell or unrelated processes.
For an entire descendant tree, use a supervisor/cgroup—e.g. run the script as a systemd service with the default `KillMode=control-group`. On Linux, another option is launching children through a wrapper that sets `PR_SET_PDEATHSIG`, though that only directly ties each process to its immediate parent.
End of response · 37 lines · 1,156 characters · sha256 4e6cbfe6e4fd84cabfa651f50930573ba69ee575043d12f2edec7741a59abf7c