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

随声附和 提交于 2019-12-07 19:44:18

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/24950251/why-sigint-can-stop-bash-in-terminal-but-not-via-kill-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!