Reputation: 413
More of a conceptual question. If I write a bash script that does something like
control_c()
{
echo goodbye
exit #$
}
trap control_c SIGINT
while true
do
sleep 10 #user wants to kill process here.
done
control+c won't exit when sleep 10 is running. Is it because linux sleep ignores SIGINT? Is there a way to circumvent this and have the user be able to cntrl+c out of a sleep?
Upvotes: 7
Views: 15943
Reputation: 531165
What you are describing is consistent with the interrupt signal going to only your bash
script, not the process group. Your script gets the signal, but sleep
does not, so your trap cannot execute until after sleep
completes. The standard trick is to run sleep
in the background and wait
on it, so that wait
receives the interrupt signal. You should also then explicitly send SIGINT
to any child processes still running, to ensure they exit.
control_c()
{
echo goodbye
kill -SIGINT $(jobs -p)
exit #$
}
trap control_c SIGINT
while true
do
sleep 10 &
wait
done
Upvotes: 13
Reputation: 411
control+c won't exit when sleep 10 is running.
That's not true. control+c DOES exit, even if sleep is running.
Are you sure your script is executing in bash? You should explicitly add "#!/bin/bash" on the first line.
Upvotes: 1
Reputation: 31
Since sleep is not bash function but external app, I guess Ctrl+C gets caught by sleep process, which normally should terminate it.
So for contorl_c function to be executed while in sleep, user must press Ctrl+C twice: 1st - to exit sleep, 2nd to get caught by bash trap.
Upvotes: 0