How to send signal to a bash script from another shell
Asked Answered
B

1

4

I start the following script which I run in a bash shell(let's say shell1) in foreground and from another shell(shell2) I send the kill -SIGUSR1 pidof(scriptA). Nothing happens. What am I doing wrong ? I tried other signals(SIGQUIT etc) but the result is same.

test_trap.sh

function iAmDone { echo "Trapped Signal"; exit 0 } 
trap iAmDone SIGUSR1 
echo "Running... " 
tail -f /dev/null # Do nothing

In shell1

./test_trap.sh

In shell2

kill -SIGUSR1 ps aux | grep [t]est_trap | awk '{print $2}'
Bionics answered 12/12, 2014 at 0:37 Comment(1)
Attention : @dennis-williamsonBionics
R
4

The trap is not executed until tail finishes. But tail never finishes. Try:

tail -f /dev/null &
wait

The trap will execute without waiting for tail to complete, but if you exit the tail will be left running. So you'll probably want a kill $! in the trap.

Rocambole answered 12/12, 2014 at 0:42 Comment(2)
Thanks! That solves the problem but I don't understand "The trap is not executed until tail finishes" part.Bionics
That's how the shell works. When a signal arrives, any traps that are set for that signal do not execute until the process that is running returns. If you want the trap to execute immediately, the shell should be sitting in wait.Rocambole

© 2022 - 2024 — McMap. All rights reserved.