Say I have a script:
#!/bin/bash
# test_trap.sh
trap "echo SIGINT captured!" SIGINT
echo $$
sleep 1000
I know trap COMMAND will only be executed after sleep 1000
finishes when it receives SIGINT signal. But the command of trap will be executed when I pressed keyboard Ctrl-C:
> sh test_sh.sh
50138
^CSIGINT captured!
And using kill -s SIGINT will not.
What am I missing here?
The bash version is GNU bash, 4.2.46(2)-release
With kill -s SIGINT 50138
, you are only sending the signal to the shell's process, and that has to wait for sleep 1000
to finish, because sleep
doesn't receive the signal.
Control-C, though, causes the terminal to send SIGINT
to every process in the current process group, so both your shell script and sleep
receive it. Your script still doesn't process the trap command until sleep
completes, but sleep
exits immediately in response to the SIGINT
it just received from the terminal.
If your kill
supports it, you can also use kill -s SIGINT -50138
(note the negative process id) to send SIGINT to the entire process group.