[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] How to trap SIGTERM?
From: |
Greg Wooledge |
Subject: |
Re: [Help-bash] How to trap SIGTERM? |
Date: |
Mon, 22 Apr 2013 08:29:02 -0400 |
User-agent: |
Mutt/1.4.2.3i |
On Sat, Apr 20, 2013 at 09:58:51PM -0600, 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.
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 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.
As mentioned already, sending SIGTERM to this script will not kill the
sleep command. The sleep command will continue running for the full
60 seconds unless you send a SIGTERM to that process also.
If you want bash to kill the sleep command when it receives the signal,
then you must put code for that into the signal trap. For example,
#!/bin/bash
unset sleep
trap 'echo TERMinated; kill $sleep; exit' TERM
sleep 60 & sleep=$!; wait
Re: [Help-bash] How to trap SIGTERM?, Pierre Gaston, 2013/04/20