Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SIGINT can stop bash in terminal but not via kill -INT?

I noticed that when I am running a hanging process via bash script like this

foo.sh:

sleep 999

If I run it via command, and press Ctrl+C

./foo.sh
^C

The sleep will be interrupted. However, when I try to kill it with SIGINT

ps aux | grep foo
kill -INT 12345  # the /bin/bash ./foo.sh process

Then it looks like bash and sleep ignores the SIGINT and keep running. This surprises me. I thought Ctrl + C is actually sending SIGINT to the foreground process, so why is that behaviors differently for Ctrl + C in terminal and kill -INT?

like image 464
Fang-Pen Lin Avatar asked Jul 25 '14 07:07

Fang-Pen Lin


People also ask

Does SIGINT terminate process?

The default action for SIGINT, SIGTERM, SIGQUIT, and SIGKILL is to terminate the process. However, SIGTERM, SIGQUIT, and SIGKILL are defined as signals to terminate the process, but SIGINT is defined as an interruption requested by the user.

How do you send SIGINT with kill?

The kill Command Thus, if you want to send signals SIGINT, SIGQUIT and SIGKILL, use INT, QUIT and KILL, respectively. If the signal name is missing, the default SIGTERM is used.

How do I stop a bash terminal?

There are many methods to quit the bash script, i.e., quit while writing a bash script, while execution, or at run time. One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.


2 Answers

CtrlC actually sends SIGINT to the foreground process group (which consists of a bash process, and a sleep process). To do the same with a kill command, send the signal to the process group, e.g:

kill -INT -12345
like image 61
ninjalj Avatar answered Oct 21 '22 20:10

ninjalj


Your script is executing "sleep 999" and when you hit CTRL-C the shell that is running the sleep command will send the SIGINT to its foreground process, sleep. However, when you tried to kill the shell script from another window with kill, you didn't target "sleep" process, you targetted the parent shell process, which is catching SIGINT. Instead, find the process ID for the "sleep 999" and kill -2 it, it should exit.

In short, you are killing 2 different processes in your test cases, and comparing apples to oranges.

root     27979 27977  0 03:33 pts/0    00:00:00 -bash   <-- CTRL-C is interpreted by shell
root     28001 27999  0 03:33 pts/1    00:00:00 -bash
root     28078 27979  0 03:49 pts/0    00:00:00 /bin/bash ./foo.sh
root     28079 28078  0 03:49 pts/0    00:00:00 sleep 100  <-- this is what you should try killing
like image 2
codenheim Avatar answered Oct 21 '22 21:10

codenheim