GPT on Question 14, Sep 20
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?A process cannot clean up children after it has died. In Bash, the usual approach is to install an EXIT trap and terminate known child PIDs before exiting:
#!/usr/bin/env bash
children=()
cleanup() {
rc=$?
trap - EXIT HUP INT TERM
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
worker1 &
children+=("$!")
worker2 &
children+=("$!")
wait "${children[@]}"
children=()Important limitations:
- •Traps do not run for
SIGKILL, kernel crashes, power loss, etc. - •This handles only the PIDs you track, not arbitrary grandchildren.
- •
pkill -P $$only finds direct children and stops working once they are reparented. - •Avoid
kill 0unless the script is deliberately placed in its own process group; otherwise it may kill its caller too.
For robust cleanup of an entire process tree, use an external supervisor or cgroup, such as a systemd service with:
[Service] ExecStart=/path/to/script KillMode=control-group
On Linux, another option for individual children is a small wrapper using prctl(PR_SET_PDEATHSIG, SIGTERM), causing the kernel to signal the child when its parent dies. Bash has no built-in interface for that, and each relevant process must arrange it itself.
In short: use an EXIT trap for normal Bash cleanup; use systemd/cgroups when cleanup must survive the parent being forcibly killed.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-20 09:06:16 UTC
- Run
- 20260920T090019Z-bbedf3
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,546 characters · 2,135 tokens out incl. hidden reasoning · 31.8 s
End of response · 52 lines · 1,546 characters · sha256 a20f1a614a579cb23166bec967b3471b663ebfa0cad18f0b09017c88578fc2eb