Ctrl-C 如何终止子进程? [英] How does Ctrl-C terminate a child process?
问题描述
我想了解 CTRL+C 如何终止子进程而不是父进程.我在一些脚本 shell 中看到了这种行为,例如 bash
,您可以在其中启动一些长时间运行的进程,然后通过输入 CTRL-C 来终止它控制权返回到外壳.
I am trying to understand how CTRL+C terminates a child but not a parent process. I see this behavior in some script shells like bash
where you can start some long-running process and then terminate it by entering CTRL-C and the control returns to the shell.
你能解释一下它是如何工作的,特别是为什么父(shell)进程没有终止?
Could you explain how does it work and in particular why isn't the parent (shell) process terminated?
shell 是否必须对 CTRL+C 事件进行一些特殊处理,如果是,它究竟是做什么的?
Does the shell have to do some special handling of CTRL+C event and if yes what exactly does it do?
推荐答案
信号默认由内核处理.旧的 Unix 系统有 15 个信号;现在他们有更多.您可以检查 (或 kill -l).CTRL+C 是名称为
SIGINT
的信号.
Signals by default are handled by the kernel. Old Unix systems had 15 signals; now they have more. You can check </usr/include/signal.h>
(or kill -l). CTRL+C is the signal with name SIGINT
.
处理每个信号的默认动作也在内核中定义,通常它会终止接收到信号的进程.
The default action for handling each signal is defined in the kernel too, and usually it terminates the process that received the signal.
所有信号(但SIGKILL
)都可以由程序处理.
All signals (but SIGKILL
) can be handled by program.
这就是shell的作用:
And this is what the shell does:
- 当 shell 在交互模式下运行时,它具有针对此模式的特殊信号处理.
- 当你运行一个程序时,例如
find
,shell:fork
s 本身- 并为孩子设置默认信号处理
- 用给定的命令替换子元素(例如用 find)
- 当你按下 CTRL+C 时,父 shell 会处理这个信号,但是子 shell 会接收到它 - 使用默认操作 - 终止.(孩子也可以实现信号处理)
- When the shell running in interactive mode, it has a special signal handling for this mode.
- When you run a program, for example
find
, the shell:fork
s itself- and for the child set the default signal handling
- replace the child with the given command (e.g. with find)
- when you press CTRL+C, parent shell handle this signal but the child will receive it - with the default action - terminate. (the child can implement signal handling too)
你也可以在你的 shell 脚本中
trap
信号......You can
trap
signals in your shell script too...你也可以为你的交互式 shell 设置信号处理,尝试在你的顶部输入它
~/.profile
.(确保您已经登录并使用另一个终端对其进行测试 - 您可以锁定自己)And you can set signal handling for your interactive shell too, try enter this at the top of you
~/.profile
. (Ensure than you're a already logged in and test it with another terminal - you can lock out yourself)trap 'echo "Dont do this"' 2
现在,每次在 shell 中按 CTRL+C 时,它都会打印一条消息.不要忘记删除该行!
Now, every time you press CTRL+C in your shell, it will print a message. Don't forget to remove the line!
如果有兴趣,您可以在源代码 这里.
If interested, you can check the plain old
/bin/sh
signal handling in the source code here.在上面的评论中有一些错误信息(现已删除),所以如果有人对此感兴趣,这是一个非常好的链接 - 信号处理的工作原理.
At the above there were some misinformations in the comments (now deleted), so if someone interested here is a very nice link - how the signal handling works.
这篇关于Ctrl-C 如何终止子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!