[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] How to trap SIGTERM?

From: Bob Proulx
Subject: Re: [Help-bash] How to trap SIGTERM?
Date: Fri, 19 Apr 2013 22:51:12 -0600
User-agent: Mutt/1.5.21 (2010-09-15)

Peng Yu wrote:
> #!/usr/bin/env bash
> echo $$
> trap "echo Booh!; exit" SIGTERM
> while true
> do
>   sleep 60
> done
> 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.

There are two serious problems with the script that should be fixed.

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.

Try this:

  #!/usr/bin/env bash
  echo $$
  trap "echo Booh!" EXIT
  while true
    sleep 60

Importantly 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.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]