GPT on Question 14, Sep 30
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?A dead Bash process cannot clean up afterward. The usual approach is to track children and use traps for normal exit and catchable signals:
#!/usr/bin/env bash
children=()
cleanup() {
status=$?
trap - EXIT INT TERM HUP
if ((${#children[@]})); then
kill -TERM -- "${children[@]}" 2>/dev/null || :
sleep 0.2
kill -KILL -- "${children[@]}" 2>/dev/null || :
wait "${children[@]}" 2>/dev/null || :
fi
exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
command1 &
children+=("$!")
command2 &
children+=("$!")
waitNotes:
- •Explicit PID tracking is safer than
pkill -P $$. - •Avoid the common
kill 0idiom unless the script owns its process group; otherwise it may kill its caller or unrelated processes. - •This kills only direct children. If children spawn descendants, run each workload in its own process group/session and kill the group, or preferably use a supervisor/cgroup.
- •No Bash trap runs for
SIGKILL, power loss, or some crashes. If cleanup must be guaranteed after abrupt death, use facilities such as a systemd service withKillMode=control-group, a container/cgroup, or Linux parent-death signals (PR_SET_PDEATHSIG) implemented by the child/helper.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-30 09:06:12 UTC
- Run
- 20260930T090007Z-45ce12
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,286 characters · 1,362 tokens out incl. hidden reasoning · 20.9 s
A dead Bash process cannot clean up afterward. The usual approach is to track children and use traps for normal exit and catchable signals:
```bash
#!/usr/bin/env bash
children=()
cleanup() {
status=$?
trap - EXIT INT TERM HUP
if ((${#children[@]})); then
kill -TERM -- "${children[@]}" 2>/dev/null || :
sleep 0.2
kill -KILL -- "${children[@]}" 2>/dev/null || :
wait "${children[@]}" 2>/dev/null || :
fi
exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
command1 &
children+=("$!")
command2 &
children+=("$!")
wait
```
Notes:
- Explicit PID tracking is safer than `pkill -P $$`.
- Avoid the common `kill 0` idiom unless the script owns its process group; otherwise it may kill its caller or unrelated processes.
- This kills only direct children. If children spawn descendants, run each workload in its own process group/session and kill the group, or preferably use a supervisor/cgroup.
- No Bash trap runs for `SIGKILL`, power loss, or some crashes. If cleanup must be guaranteed after abrupt death, use facilities such as a systemd service with `KillMode=control-group`, a container/cgroup, or Linux parent-death signals (`PR_SET_PDEATHSIG`) implemented by the child/helper.
End of response · 41 lines · 1,286 characters · sha256 6b03fc9b53b4f877616c08f742420cb8632b5e5229360e836d75706300491aa3