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?
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.
“ 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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With