GPT on Question 14, Sep 29
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?There are two cases:
Normal script exit: trap and reap direct children
#!/usr/bin/env bash
children=()
cleanup() {
trap - EXIT INT TERM
((${#children[@]})) && kill -TERM "${children[@]}" 2>/dev/null
wait "${children[@]}" 2>/dev/null
}
trap cleanup EXIT INT TERM
worker1 & children+=("$!")
worker2 & children+=("$!")
waitThis handles ordinary exit and catchable signals. wait is important: killing children is not the same as reaping them.
Parent is killed or crashes
A Bash trap cannot run after SIGKILL, machine failure, etc. The idiomatic robust solution is to use an external supervisor/cgroup, such as a systemd service:
[Service] ExecStart=/path/to/script KillMode=control-group
That lets systemd terminate every process remaining in the service’s cgroup, including grandchildren.
On Linux, another option is to launch each child with a parent-death signal:
setpriv --pdeathsig TERM -- worker1 &
This uses PR_SET_PDEATHSIG, but applies to the direct child, not automatically to its descendants.
Avoid relying on PPID, kill -0 "$parent", or broad pkill matching: they have races and PID-reuse hazards. If you must clean up an entire descendant tree after an uncatchable parent death, cgroup-based supervision is generally the best approach.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-29 09:05:42 UTC
- Run
- 20260929T090007Z-334891
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,329 characters · 845 tokens out incl. hidden reasoning · 13.6 s
End of response · 45 lines · 1,329 characters · sha256 ed3b07b37646b9f89d3518b45ad6fa5042b8810f10f51bdb5ba6b05d554b80f9