Linux: How to kill Sleep
Solution 1
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
Solution 2
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.
J.Doe
Updated on June 23, 2022Comments
-
J.Doe almost 2 years
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?
-
Rakholiya Jenish over 8 years
-
-
Keith Thompson over 8 yearsWhen I run the script on my system (after adding
#!/bin/bash
), typing Ctrl-C before thesleep 10
finishes causes the script to terminate after printinggoodbye
. -
alper almost 4 years
ctrl-d
orctrl-c
(prints^C
) had no affect is it normal?