Linux: How to kill Sleep

11,511

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.

Share:
11,511
J.Doe
Author by

J.Doe

Updated on June 23, 2022

Comments

  • J.Doe
    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?

  • Keith Thompson
    Keith Thompson over 8 years
    When I run the script on my system (after adding #!/bin/bash), typing Ctrl-C before the sleep 10 finishes causes the script to terminate after printing goodbye.
  • alper
    alper almost 4 years
    ctrl-d or ctrl-c (prints ^C) had no affect is it normal?