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

Details what happens when you press Ctrl-C in a terminal? Yes, I know that he sends SIGINT, but what steps need to be taken to get there?

I did some research, so I think I understand most of the picture, but not all.

For pedagogy, I assume that we run the xterm terminal emulator in an X session. The terminal launches the Bash shell, and the shell currently runs some long pipeline, consisting of several processes in the foreground.

  • I press Ctrl-C on the keyboard.
  • X dispatches a keyboard event to xterm.
  • Does xterm translate the Ctrl-C keyboard event and send it to the handle of the main pseudo-tty file it holds? (Some kind of magic happens)
  • The kernel detects that some special SIGINT event occurs on the pseudo-tty and finds a session whose control terminal is tty. It sends SIGINT to the current foreground process group of this session, which includes only the processes in our pipeline.

My question is, as far as I understand correctly, and how exactly does xterm tell the kernel to send SIGINT to a session with this control terminal?

+5
source share
1 answer

tl; dr core does this.

Each pty (pseudo tty) has two ends, a master and a subordinate. In the example xterm, xterm will be held in the descriptor of the main file. Any keystrokes are recorded directly in master fd. The slave fd (pts or pte slave) belongs to the session and is transmitted regardless of what the foreground process group is.

Whenever an ASCII ETX character (^ C) is written to the master, the kernel translates it into SIGINT in the foreground process group with the corresponding control terminal. This is really a pty setup. You can run stty -a and see that by default it is intr = ^C; , which means ^C , or ETX is the symbol "SIGINT". This can be changed to another character or completely disabled.

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

+2
source

Source: https://habr.com/ru/post/1271414/


All Articles