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.
Could you explain how does it work and in particular why isn't the parent (shell) process terminated?
Does the shell have to do some special handling of CTRL+C event and if yes what exactly does it do?
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.
All signals (but SIGKILL
) can be handled by program.
And this is what the shell does:
find
, the shell:
fork
s itselfYou can trap
signals in your shell script too...
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
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.