In detail, what happens when you press Ctrl-C in a terminal?

时间秒杀一切 提交于 2019-12-03 15:52:25

tl;dr the kernel does it.

Each pty (pseudo tty) has two ends, a master and a slave. In the xterm example, xterm would be holding onto the master file descriptor. Any key presses are written directly into the master fd. The slave fd (pts, or pty slave) is owned by a session and passed to whatever the foreground process group is.

Whenever an ASCII ETX character (^C) is written to the master, the kernel translates that into sending SIGINT to the foreground process group with the corresponding controlling terminal. This is actually a pty setting. You can run stty -a and see that the default is intr = ^C;, meaning ^C or ETX is the "SIGINT" character. This can be changed to a different character or disabled entirely.

A more complex example would be how Ctrl-C works through an interactive SSH session. Interactive SSH sessions allocate a pty on the server side. The client side pty is set to raw mode, meaning that the client side kernel will not translate ETX into SIGINT. Instead, the client side kernel passes the ETX along to the slave. In this case, the ssh client process takes that ETX and passes it along to the server sshd process. If the server sshd pty is not in raw mode, then the server's kernel will translate that ETX into a SIGINT to its foreground process group. This is how Ctrl-C sends SIGINT to the process running on the server instead of killing your client side SSH and leaving you hanging.

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