|Subject:||Re: [Help-bash] How to trap SIGTERM?|
|Date:||Sat, 20 Apr 2013 11:18:22 +0300|
Peng Yu wrote:There are two serious problems with the script that should be fixed.
> #!/usr/bin/env bash
> echo $$
> trap "echo Booh!; exit" SIGTERM
> while true
> sleep 60
> I have the above script. I run it and get the process id. Then I use
> "kill -SIGTERM pid" to kill it. But the script fails to respond. Does
> anybody know how to get the script respond to SIGTERM? Thanks.
If you trap a signal then you should not simply "exit". That rewrites
the exit code and hides the kill-on-signal. Instead you should have
the script kill itself.
trap "echo foo 1>&2; trap - TERM; kill -TERM $$" TERM
But that is only *if* you need to catch the signal. In your example
here you do not. Instead with bash if you have things to do at shell
exit time then use the "EXIT" trap case. And do not call exit from
the EXIT trap.
trap "echo Booh!" EXIT
while trueImportantly notice that the exit code is now correct when you kill it
with a signal.
Note however that the sleep is cast adrift and isn't killed just
because the script interpreter bash parent is killed. It will run
until it exits unless it is also killed.
|[Prev in Thread]||Current Thread||[Next in Thread]|