Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: How to kill Sleep

Tags:

linux

bash

sleep

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?

like image 827
J.Doe Avatar asked Aug 17 '15 01:08

J.Doe


People also ask

How do I kill a sleeping process in Linux?

Terminating a Process using kill Command You can use either the ps or pgrep command to locate the PID of the process. Also, you can terminate several processes at the same time by entering multiple PIDs on a single command line. Lets see an example of kill command. We would kill the process 'sleep 400' as shown below.

What is kill 9 in Linux?

“ kill -9” command sends a kill signal to terminate any process immediately when attached with a PID or a processname. It is a forceful way to kill/terminate a or set of processes. “ kill -9 <pid> / <processname>” sends SIGKILL (9) — Kill signal. This signal cannot be handled (caught), ignored or blocked.

How do you kill a range of processes in Linux?

In order to kill multiple processes at once, we just specify all of the relevant process IDs in our kill command. The kill command will send a TERM signal to the processes by default. This can be changed by using a command flag. For example, the -9 flag will send a KILL signal instead.


2 Answers

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
like image 61
chepner Avatar answered Oct 08 '22 23:10

chepner


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.

like image 35
Kal Avatar answered Oct 08 '22 23:10

Kal