Odi's astoundingly incomplete notes
New entries | CodeRelaying SIGINT signal to child processes
Here is a bash function (plus test program) that correctly relays important signals to child processes. So that pressing Ctrl-C reliably terminates both all child processes and the parent process.
- Delivers interrrupt signals also to parent process again (after removing signal handler)
- SIGPIPE is only sent to children
- Works for any number of child processes
- Does not work for SIGKILL (no signal is delivered to app in that case)
#!/bin/bash relay() { PIDS="" for PID in $(pgrep -P $$); do PIDS="${PIDS} ${PID}" done trap "kill -PIPE ${PIDS}" PIPE PIDS="${PIDS} $$" #echo "setting up traps to ${PIDS}" trap "trap - HUP; kill -HUP ${PIDS}" HUP trap "trap - INT; kill -INT ${PIDS}" INT trap "trap - QUIT; kill -QUIT ${PIDS}" QUIT trap "trap - TERM; kill -TERM ${PIDS}" TERM } (sleep 10; echo '1st subshell was not killed')& relay $! (sleep 10; echo '2nd subshell was not killed')& relay $! echo 'please hit Ctrl-C within 10s' sleep 10 wait echo 'main shell was not killed'
Add comment