GPT on Question 14, Sep 25
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?The usual Bash pattern is to track child PIDs and clean them up from an EXIT trap:
#!/usr/bin/env bash
children=()
cleanup() {
rc=$?
trap - EXIT HUP INT TERM
if ((${#children[@]})); then
kill -TERM -- "${children[@]}" 2>/dev/null || true
for pid in "${children[@]}"; do
wait "$pid" 2>/dev/null || true
done
fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
worker_one &
children+=("$!")
worker_two &
children+=("$!")
wait "${children[@]}"This handles normal exit and catchable signals. It does not run if the parent is killed with SIGKILL, the machine crashes, etc.
If children may create grandchildren, PID tracking is insufficient. On Linux, start each workload in its own process group/session and kill the group:
groups=()
setsid worker_one &
groups+=("$!")
cleanup() {
rc=$?
trap - EXIT HUP INT TERM
for pgid in "${groups[@]}"; do
kill -TERM -- "-$pgid" 2>/dev/null || true
done
wait 2>/dev/null || true
exit "$rc"
}Avoid kill 0: it kills the shell’s entire process group and may include the invoking shell or unrelated processes.
For cleanup that must also work after an uncatchable parent death, Bash alone cannot guarantee it. Use one of:
- •a service manager/cgroup, such as systemd with
KillMode=control-group - •a small launcher using Linux
prctl(PR_SET_PDEATHSIG, SIGTERM) - •children that monitor a pipe from the parent and exit on EOF
For production process-tree management, a service manager/cgroup is generally the most reliable option.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-25 09:06:26 UTC
- Run
- 20260925T090007Z-f08d1f
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,642 characters · 1,945 tokens out incl. hidden reasoning · 29.0 s
End of response · 67 lines · 1,642 characters · sha256 9bae49dabfb14233ab434f6ea30ec21eabfef211b2fef2c15c9a92124768fbba