'In bash script, what happens when a signal is trapped
Suppose I am running the following example saved as hello.sh
#!/bin/bash
hello() {
echo "hello"
}
trap "hello" INT
sleep 100
echo "end"
and in shell I start hello.sh. After 1 second I press Ctrl-C.
Please treat sleep as any long-run process that I started.
Here are my questions:
- When
SIGINTis generated, is it delivered tosleepdirectly or to the shell script? - If it is the second, can I let
sleephas a chance to handle theSIGINTand do not propagate to its parenthello.sh? - If it is the first, what is the status of
sleepafter thehellofunction is finished?
My tests made me feel that the following occurred in order
sleepstarted to runhello.shreceived the signal- function
hellostarted to run - function
hellofinished echo "end"started to run- the script exits.
But at which stage the sleep process exits and because of what (e.g. the SIGINT stopped the sleep process?)
Solution 1:[1]
$ cat foo.sh
_sigint()
{
echo "received SIGINT"
}
trap _sigint INT
sleep 10000
echo "status=$?"
$ bash foo.sh # <-- start foo.sh and then press CTRL-C
^Creceived SIGINT
status=130
Some explanation:
sleepruns as a child process ofbash.bashandsleepare running in the same process group which is now the foreground process group.When CTRT-C is pressed, it'll generate
SIGINTand the signal will be sent to all processes in the foreground process group so bothbashandsleepwill receiveSIGINT.According to bash manual (can also see
man bash)If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes.
So here
bashwould wait forsleepto be killed (The default SIGINT behavior is to terminate the process. See signal(7)) first and thenbashruns itsSIGINTtrap.According to bash manaul
The return value of a simple command is its exit status, or
128+nif the command is terminated by signaln.The
SIGINTis 2 (seekill -l) sosleep's exit status is128+2=130.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
