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

谁说我不能喝 提交于 2020-01-01 05:33:07

问题


In detail, what happens when you press Ctrl-C in a terminal? Yes, I know that it sends SIGINT, but what steps does it take to get there?

I have done some research so I think I understand most of the picture, but not all of it.

For the sake of pedagogy, I will assume we are running a terminal emulator, xterm, in an X session. The terminal is running the Bash shell, and the shell is currently running some long running pipeline consisting of multiple processes in the foreground.

  1. I press Ctrl-C in the keyboard.
  2. X sends the keyboard event to xterm.
  3. xterm translates the Ctrl-C keyboard event and sends it to the pseudo-tty master file descriptor it is holding? (Some magic happens)
  4. The kernel detects that some special SIGINT event happens on the pseudo-tty, and finds the session whose controlling terminal is this tty. It sends SIGINT to the current foreground process group of that session, which includes only the processes in our pipeline.

My question is, is my understanding so far correct, and how exactly does xterm tell the kernel to send SIGINT to the session with a given controlling terminal?


回答1:


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.



来源:https://stackoverflow.com/questions/45993444/in-detail-what-happens-when-you-press-ctrl-c-in-a-terminal

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