Pithikos Pithikos - 4 months ago 18
Bash Question

Sending SIGINT to foreground process works but not background

I have two scripts. script1 spawns script2 and then sends a

SIGINT
signal to it. However the trap in script2 doesn't seem to work?!

script1:

#!/bin/bash
./script2 &
sleep 1
kill -SIGINT $!
sleep 2


script2:

#!/bin/bash
echo "~~ENTRY"
trap 'echo you hit ctrl-c, waking up...' SIGINT
sleep infinity
echo "~~EXIT"


If change
./script2 &
to
./script2
and press
CTRL+C
the whole things works fine. So what am I doing wrong?

Answer

I guess what you are trying to achieve is that when script2 receives the SIGINT it continues and prints the message. Then, you need

#!/bin/bash
echo "~~ENTRY"
trap 'echo you hit ctrl-c, waking up...; CONT=true' SIGINT
CONT=false
while ! $CONT
do
   sleep 1
done
echo "~~EXIT"