Section 12.42

termios and tty

Full name: Terminal input/output interface (termios) and teletypewriter (tty).

Definition

termios is the POSIX (Portable Operating System Interface) interface for reading and changing the settings of a terminal device; Python’s §12.23 termios module exposes it. A tty, short for teletypewriter, is a terminal device: a serial port, a console, or a pseudo-terminal, the software terminal behind a terminal window. Between a program’s reads and writes and the device, the kernel runs a line discipline, a layer that can collect and edit input lines, echo input, translate bytes and act on control characters. The termios settings switch each action on or off.

The idea

A program reads binary frames from a sensor attached through a serial port, for example a USB adapter that appears as /dev/ttyUSB0. The sensor sends correct bytes, yet the program sees some bytes changed and others missing, and sometimes a read never returns. Nothing is wrong with the wire. The device file is a terminal, and terminals were designed for people typing text: the kernel collects input until the user presses Enter, lets the user correct typing mistakes, turns the carriage-return key into a newline, and treats some control characters as commands.

That processing, the line discipline, helps a person at a keyboard and damages binary data, in which every byte value from 0x00 to 0xFF can occur and none is a command. The repair is to switch the terminal into raw mode, in which the line discipline passes every byte through unchanged and makes it available at once. A fair picture is a secretary who sits between the line and the program and tidies every message: useful for dictated letters, harmful for a table of numbers, until told to pass everything on untouched.

How it works

The settings form a termios structure with four sets of flags and an array §14.5 of special characters. In Python, termios.tcgetattr(fd) returns them as the list [iflag, oflag, cflag, lflag, ispeed, ospeed, cc], and termios.tcsetattr(fd, when, attrs) writes them back. The flags that decide whether bytes pass unchanged are these; the byte values are the Linux defaults.

Canonical mode (ICANON on). The line discipline collects input in a line buffer, and read returns only when a line is complete: when LF arrives, or one of the optional end-of-line bytes set in VEOL and VEOL2, or 0x04 (Ctrl-D, the end-of-file character). A read returns at most one line, and 0x04 at the start of a line makes it return 0 bytes. While collecting, the line discipline edits the buffer: 0x7F, the erase character, deletes the previous byte, and 0x15 (Ctrl-U), the kill character, deletes the whole line; both are themselves discarded. On Linux a line holds at most 4096 bytes including its newline, and further bytes are discarded.

Noncanonical mode (ICANON off). Bytes become readable as they arrive. Two entries of the cc array decide when read returns: VMIN, a byte count, and VTIME, a time in tenths of a second.

A read never returns more than the number of bytes requested, and 0 bytes in this mode means that nothing arrived in time, not end of file.

Raw mode. The C function cfmakeraw, which is not part of POSIX but exists on Linux and many other Unix-like systems, gives the usual raw settings. It clears IGNBRK, BRKINT, PARMRK, ISTRIP, INLCR, IGNCR, ICRNL and IXON in the input flags, OPOST in the output flags, ECHO, ECHONL, ICANON, ISIG and IEXTEN in the local flags, and parity, and it selects 8 data bits. It leaves IXOFF alone. Python’s tty.setraw(fd) switches a descriptor to raw mode in one call. Since Python 3.12 it also clears IXOFF and the other POSIX input and local flags, sets VMIN = 1 and VTIME = 0, and returns the previous settings; earlier versions cleared fewer flags. tty.setcbreak(fd) turns off only echo and canonical mode. The serial library pyserial §12.36 puts a port into raw mode when it opens it.

Applying settings. The argument when of tcsetattr chooses the moment: TCSANOW at once, TCSADRAIN after all queued output has been sent, TCSAFLUSH after that and also discarding input not yet read. tcsetattr reports success if any of the requested changes was carried out, so a program that needs all of them reads the settings back with tcgetattr and compares. The settings belong to the device, not to the program: they stay in force after the program exits, and the next program that opens the device starts with them. A program therefore saves the settings before changing them and restores them in a finally block.

Worked example

A sensor sends the 5 bytes 55 0D 41 7F 42, written in hexadecimal, and then nothing. The port has ICANON and ICRNL on and every other flag that changes input off, and the program calls os.read(fd, 100) twice.

  1. 0x55 enters the line buffer, which now holds 1 byte.

  2. 0x0D is turned into 0x0A by ICRNL. 0x0A ends a line, so the first read returns the 2 bytes 55 0A. The program sees 0x0A where the sensor sent 0x0D.

  3. 0x41 starts a new line: the buffer holds 1 byte.

  4. 0x7F is the erase character. It deletes 0x41 and is itself discarded, so the buffer is empty.

  5. 0x42 enters the buffer: 1 byte. No line end follows, so the second read waits forever.

Of the 5 bytes sent, the program received 2, one of them altered; 2 bytes were destroyed and 1 is stuck. A checksum §4.32 over the frame fails, or is never computed because the frame never arrives.

In the other direction, with OPOST and ONLCR on, the program writes the 3 bytes 10 0A 20, and the sensor receives the 4 bytes 10 0D 0A 20, one byte more than was written.

After tty.setraw(fd) under Python 3.12, which sets VMIN = 1 and VTIME = 0, the same 5 bytes arrive unchanged. A read returns as soon as at least 1 byte is available, so the first read may return any count from 1 to 5, depending on timing. The program keeps reading until its own framing rule, such as length-prefix framing §4.30, says that a frame is complete.

Stated precisely

In the receiving direction, a terminal device passes every byte unchanged, in order and without waiting for a line end when ICANON, ISIG and IEXTEN are off; ICRNL, INLCR, IGNCR, ISTRIP, IXON and PARMRK are off, as is IUCLC, a flag outside POSIX with which Linux turns capital letters into small ones; and the line uses 8 data bits (CS8) without parity. In the sending direction, the bytes the program writes leave unchanged and with nothing added when OPOST, IXOFF and ECHO are off; ECHO counts here because it adds received bytes to the outgoing stream.

With those settings, read returns between 1 and the requested number of bytes as the VMIN and VTIME rules allow, or 0 bytes when no byte arrived in time. Nothing more is guaranteed: the bytes carry no frame boundaries, bytes lost before reaching the kernel (because of a wrong bit rate, or because a receive buffer was full) are not reported as lost, and restoring old settings does not undo bytes already sent or changes already made in the device at the other end.

Limits and common mistakes

Opening a device does not reset its settings. A port may still have the settings of the program that used it last, so a program sets every flag it depends on, then checks them with tcgetattr.

With ECHO on, every received byte goes back to the sender. A device that reads its input as commands then receives its own output as commands.

Pseudo-terminals have a line discipline too. A program that reaches a device through a terminal emulator, or through a tool that presents the device as a pseudo-terminal, needs raw mode on that pseudo-terminal as well.

A USB CDC ACM §6.24 device (Communications Device Class, Abstract Control Model: the standard way for a USB device to appear as a serial port) appears as a terminal device such as /dev/ttyACM0, so the same line discipline applies on the computer’s side. A device without a real UART behind it may ignore the bit rate.

A program that crashes while an interactive terminal is in raw mode leaves the user’s shell without line editing or echo; the command stty sane restores usable settings.

Windows has no termios. Its serial ports are configured through a different interface, which pyserial hides behind the same Python calls.

Questions answered

Could line discipline modify bytes or wait for a newline?

Yes. The line discipline, the kernel layer between a terminal device and the program that reads it, does both unless the program turns the corresponding termios settings off. It waits for a newline in canonical mode (flag ICANON), where read returns only when a line ends with LF (line feed, 0x0A), another configured end-of-line byte or the end-of-file character 0x04. It modifies bytes in six ways: input translation (ICRNL turns CR, carriage return 0x0D, into LF; ISTRIP clears the top bit); line editing (0x7F deletes the previous byte and 0x15 the whole line); signal characters (with ISIG, 0x03 is removed and a signal is sent); software flow control (with IXON, 0x11 and 0x13 are removed); output processing (with OPOST and ONLCR, each LF written becomes CR LF); and echo, which sends received bytes back out.

For binary data, put the device into raw mode (with cfmakeraw, Python’s tty.setraw, or a library such as pyserial that does it on opening), confirm with tcgetattr that every change took effect, and still frame and check the records in the program, because raw mode passes bytes unchanged but marks no record boundaries.

Related entries: pyserial (§12.36), select and polling (§12.43), Length-prefix framing (§4.30), UART (§6.23), USB CDC ACM (§6.24), Checksum versus CRC (§4.32). Further reading: [128, 189].