[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: Thu, 25 Apr 2013 18:25:25 -0600
User-agent: Mutt/1.5.21 (2010-09-15)

Greg Wooledge wrote:
> Bob Proulx wrote:
> > How is SIGTERM any different from SIGHUP, SIGINT or SIGQUIT?  Many
> > daemons catch and handle SIGHUP as a normal operation to go re-read
> > their configuration file for example.  But of course it keeps running
> > in that case.
> The question isn't how SIGTERM differs from other signals, but rather,
> how SIGINT differs from other signals.  It's SIGINT that has the
> special requirement of resending the signal to yourself.

Any caught signal needs to be sent to itself.  Otherwise the passed
back to wait(2) status will be incorrect.

> Anyway.  The original poster's question was "Why doesn't my signal
> handler fire immediately when I SIGTERM bash which is running sleep
> in the foreground?"  The answer to that is: bash is waiting for sleep
> to exit, and will not receive the SIGTERM until that happens.

If running from the terminal and Control-C is pressed then SIGINT will
be sent to the entire foreground process group.  The sleep subprocess
will be killed by it along with everything else and then bash can exit
immediately.  That is the difference between C-c and sending a normal
process kill from the command line.  Of course you could send a signal
to the entire process group and have a similar effect.

> If you want bash to process a signal immediately, without waiting for
> a command to terminate, then you need the long-running command to be
> running in the background, with bash doing a "wait" or a "read", or
> perhaps one of a small handful of other builtins.
> #!/bin/bash
> trap 'echo TERMinated; exit' TERM
> sleep 60 & wait
> Sending SIGTERM to this script will cause the script to print "TERMinated"
> and exit, which I believe is what the original poster wants.

That "exit" in the TERM trap above is still incorrect as it will wash
out the exit code and end up with $? being 0.  If exiting zero-success
is desired then fine.  But most of the time exiting due to a signal
should result in a failure exit code.  And in addition to being a
failure exit code it should be the *right* failure exit code which is
only obtained by sending the signal to self.


reply via email to

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