GPT on Question 14, Oct 2
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?In Bash, use an EXIT trap and track child PIDs:
#!/usr/bin/env bash
children=()
cleanup() {
trap - EXIT
((${#children[@]})) || return
kill -TERM "${children[@]}" 2>/dev/null || true
wait "${children[@]}" 2>/dev/null || true
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
some_command &
children+=("$!")
another_command &
children+=("$!")
waitThis handles normal exit and catchable signals, but only guarantees cleanup of the recorded direct children.
If commands can create grandchildren, put the script in its own process group/session and terminate the whole group:
setsid ./worker.sh
Then, inside worker.sh, an EXIT trap can signal its process group:
cleanup() {
trap - EXIT
trap '' TERM
kill -TERM -- "-$$" 2>/dev/null || true
}
trap cleanup EXITOnly use kill -- -$$ when the script is definitely its own process-group leader, such as when launched with setsid; otherwise it may kill the invoking shell or unrelated processes.
No Bash trap runs after SIGKILL, kernel panic, or similar abrupt death. For a hard guarantee, use an external supervisor/cgroup—typically a systemd service with KillMode=control-group—or, on Linux, a small wrapper using prctl(PR_SET_PDEATHSIG, ...).
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-10-02 09:06:15 UTC
- Run
- 20261002T090008Z-e178a0
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,311 characters · 1,376 tokens out incl. hidden reasoning · 19.9 s
End of response · 51 lines · 1,311 characters · sha256 50ccd592780d270b4d0bf935ac8de602433ead2e9cf47c8bc19c3a6934cbccc5