I have seen trap 'kill $(jobs -p)' EXIT
in shell scripts which sends SIGTERM to all the jobs of the shell when this shell closes. If one executes a bash script, then new bash shell is started. For example here user executes ./trap_test.sh
and this creates a bash instance with PID 98959
:
| | |-+= 05624 user /usr/local/bin/bash
| | | \-+= 98959 user /bin/bash ./trap_test.sh
| | | \--- 98960 user sleep 10
Under which circumstances it is possible that job is still running while the parent shell is closed? In the example above if I kill PID 98959 then PID 98960 is killed automatically. trap 'kill $(jobs -p)' EXIT
seems to be useless to me as all the child processes should be killed anyway when the shell itself is closed.
sleep 10
simply finished at the time when I sent the SIGTERM to98959
. If I use longer sleep time and kill the PID98959
, then PID1
becomes the parent process ID of98960
. In a nutshell,trap 'kill $(jobs -p)' EXIT
is not useless.