UNIX terminal I/O


I read and learned about terminal I/O on UNIX systems. Some of the more key concepts are documented here.


One of the reasons terminal I/O is complex is that it is used for many things.


Two working modes of terminal I/O: normal mode input processing (default), non-normal mode input processing.

In canonical mode, the terminal driver returns at most one line for each read request.

Terminal devices can be considered to be controlled by the terminal driver in the kernel, and each terminal device has an input queue and an output queue.

When echoing is turned on, there is an implicit connection between the input queue and the output queue.

The input queue length is a finite value.

Although the output queue is also limited, the program cannot obtain this value. When the output queue is about to fill up, the kernel will directly put the writing process to sleep.

Most UNIX systems do all the specification processing in a module called the terminal line discipline. This module is between the kernel generic read and write functions and the actual device driver.

All terminal device characteristics that can be detected and changed are contained in the termios structure.

Use tcsetattr and tcgetattr to set terminal options and control the terminal.

special input characters

POSIX defines 11 characters to be treated specially on input. Among these 11 special characters, the value of 9 characters can be changed arbitrarily.

In order to change the special characters, the corresponding entry of the c_cc array in the termios structure needs to be modified.

POSIX allows these characters to be forbidden.


On most versions of UNIX systems, the controlling terminal name has always been /dev/tty.

Canonical Modewith non-canonical mode

Canonical Mode: Send a request, and the terminal program returns immediately after a line has been entered. The following conditions cause the read to return:

  1. It is not necessary to read a complete line when the requested number of bytes has been read.
  2. When reading a line delimiter
  3. The signal is caught and the function no longer restarts automatically

Non-canonical mode: When input data is not assembled into lines, special characters are not processed. After reading the specified amount of data, or after the specified amount of time, notify the system to return. Signal processing is not turned off in this mode, and the user can always type a character that triggers the terminal to generate a signal.

terminal window size

Most UNIX systems provide a way to track the current terminal window size and cause the kernel to notify the foreground process group when the window size changes. The kernel maintains a winsize structure for each terminal and pseudo-terminal.