GPT on Question 14, Sep 26
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?In Bash, the usual pattern is to trap shell exit/signals, terminate the children, and wait for them:
#!/usr/bin/env bash
children=()
cleanup() {
status=$?
trap - EXIT HUP INT TERM
if ((${#children[@]})); then
kill -TERM "${children[@]}" 2>/dev/null || true
wait "${children[@]}" 2>/dev/null || true
fi
exit "$status"
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
worker_one &
children+=("$!")
worker_two &
children+=("$!")
waitThis handles normal exit and catchable signals. It cannot handle SIGKILL, power loss, or the shell crashing before its traps run.
If workers create grandchildren, killing only their PIDs may not be enough. Put each worker in its own process group/session and terminate the group:
setsid worker &
pgid=$!
cleanup() {
status=$?
trap - EXIT HUP INT TERM
kill -TERM -- "-$pgid" 2>/dev/null || true
wait "$pgid" 2>/dev/null || true
exit "$status"
}This assumes the worker does not deliberately escape by creating another session. For production services, the most reliable approach is to use a supervisor such as systemd with KillMode=control-group; Bash alone cannot guarantee cleanup after an uncatchable parent death. On Linux, another option is having each child request PR_SET_PDEATHSIG, but that requires support in the child or a small wrapper—Bash has no built-in for it.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-26 09:05:46 UTC
- Run
- 20260926T090007Z-89c0b7
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,440 characters · 1,405 tokens out incl. hidden reasoning · 21.3 s
End of response · 51 lines · 1,440 characters · sha256 eca2942cf7daab598af388bbf699b1f54ef3c6bcf6da84b786ec3b2c31b7abb5