GPT on Question 14, Sep 16
I'm writing a bash script to purge orphaned children after the parent dies. What's the idiomatic way?In Bash, trap termination and explicitly clean up the children you started:
#!/usr/bin/env bash
children=()
cleanup() {
rc=$?
trap - EXIT INT TERM
if ((${#children[@]})); then
kill -TERM "${children[@]}" 2>/dev/null || :
wait "${children[@]}" 2>/dev/null || :
fi
exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
worker1 &
children+=("$!")
worker2 &
children+=("$!")
waitThis handles normal exit and catchable signals. It does not handle the parent being killed with SIGKILL, crashing before cleanup, or grandchildren that detach.
For a whole process tree, the more robust idiom is to run the script in its own process group/session and terminate that group, or preferably use a supervisor such as systemd with a cgroup:
systemd-run --user --scope ./script.sh
On Linux, if each child must die immediately when its parent disappears—even after SIGKILL—have the child set:
prctl(PR_SET_PDEATHSIG, SIGTERM);
via a small wrapper before exec. Check the parent PID again after prctl to avoid the parent-death race.
Avoid blindly using trap 'kill 0' EXIT: it signals the shell’s entire process group and may kill the invoking shell or unrelated processes unless you deliberately created a separate process group.
Exact recordShowHideThe model id, the run, the verbatim text with line numbers and its full sha256
- Scored
- answered
- Received
- 2026-09-16 09:06:16 UTC
- Run
- 20260916T090004Z-fdcf7b
- Served by
- OpenAI · HTTP 200 · finish stop
- Size
- 1,327 characters · 846 tokens out incl. hidden reasoning · 13.6 s
End of response · 49 lines · 1,327 characters · sha256 f4c9308521dea633bdc8908b85b0c31778c0e3f53140557c7ea7213462868761