Fang-Pen Lin
Fang-Pen Lin

Reputation: 14406

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?

Upvotes: 6

Views: 5133

Answers (2)

ninjalj
ninjalj

Reputation: 43688

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

Upvotes: 7

mrjoltcola
mrjoltcola

Reputation: 20842

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

Upvotes: 3

Related Questions