GPT on Question 14, Oct 1
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?There is no fully reliable, portable Bash-only mechanism: an EXIT trap does not run if the parent receives SIGKILL, crashes, or the machine loses power.
For normal exits and catchable signals, track child PIDs and clean them up:
#!/usr/bin/env bash
children=()
cleanup() {
trap - EXIT INT TERM HUP
if ((${#children[@]})); then
kill -TERM -- "${children[@]}" 2>/dev/null || true
wait "${children[@]}" 2>/dev/null || true
fi
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
worker1 & children+=("$!")
worker2 & children+=("$!")
waitAvoid relying on pkill -P $$: it only finds direct children, races with reparenting, and does not handle grandchildren reliably.
If cleanup must also happen after SIGKILL or a crash, use OS-level supervision:
- •systemd/cgroups: run the script as a service with
KillMode=control-group—usually the best Linux solution. - •Linux parent-death signal: start each child with a wrapper such as:
setpriv --pdeathsig TERM -- worker &
This requires a sufficiently recent util-linux, and only signals that direct child; descendants need their own handling.
- •A dedicated supervisor/container runtime can likewise terminate the whole process group or cgroup.
In short: use traps for orderly Bash cleanup, and a supervisor/cgroup when cleanup must be guaranteed after abrupt parent death.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-10-01 09:06:04 UTC
- Run
- 20261001T090007Z-857bc9
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,431 characters · 1,840 tokens out incl. hidden reasoning · 32.9 s
End of response · 44 lines · 1,431 characters · sha256 9d204768f939ae4548c9b44d8aa73e6f4e96165f38b362f4e5adb4c9cb1da135