The term “terminal” is often used to refer to the software emulation of the traditional physical terminal in history12. Apps that emulate this type of device are called “terminal emulators”.

ASCII text were transmitted over the wire as it was typed on the terminal. The kernel of the mainframe would decode it. The text gets sent to a driver called the TTY driver. This then gets sent as input to user programs. Kernels returns output back to the teletype

teletype

Line Discipline

Line discipline part of the TTY Driver layer in terminal emulator software that buffers characters into kernel memory, allowing buffers to be editable. Terminal apps are OS supervised processes that listen for events and input from the user and tell the OS what to display. Line discipline provides key functionality for terminal emulation:

Input Processing: Keystroke processing before they reach the application. This includes signal interrupts, suspends EOF’s and line editing features like backspace.

Output Processing: Post processing of output before it’s displayed, such as newline conversion, tab expansion and character formatting.

Canonical vs Raw Mode: Canonical (cooked) mode, characters are buffered until “enter/return” pressed. Raw mode, characters are passed through without buffer or post-processing.

Shell

The terminal and shell are separate programs with separate concerns. The work of running other programs as processes and interpeting commands is done by the shell 1.

Initialization: The terminal spawns the shell process.

Process spawning: The shell creates child processes for each command the user runs.

”PTY”

The terminal must have a way to communicate with the shell. This is done by streaming characters the same way physical terminals once did. In software terminal emulators, traditional wires and TTY are replaced with pairs of file descriptors called pseudo-TTY (PTY). The kernel possesses a TTY driver with a line discipline for the two opposite ends of the PTY.

terminal-shell-tty

Key Input:

  1. Terminal Emulator receives keystrokes
  2. Terminal Emulator writes to the PTY leader file descriptor
  3. PTY leader communicates with the TTY driver in kernel space
  4. TTY driver forwards data to the PTY follower
  5. Shell reads from its stdin (which is the PTY follower)

Key Output (reverse):

  1. Shell writes to stdout/stderr (PTY follower)
  2. TTY driver processes the data
  3. PTY leader receives it from the TTY driver
  4. Terminal Emulator reads from PTY leader and displays it

Footnotes

  1. Why Is It Called a Terminal “Emulator”? 2

  2. What is a Terminal Emulator?