Canonical Versus Non-Canonical Modes
The line discipline operates in two primary modes: canonical and non-canonical. In canonical mode, the terminal driver buffers input until a newline character (\n) is encountered. This allows for basic line editing within the kernel: backspace, delete, and line-kill signals are handled before the shell ever sees the buffer. This offloads the burden of basic input correction from the application to the kernel, ensuring consistency across tools.
In non-canonical mode, the buffer is bypassed. Data is passed to the application immediately or after a specific count of bytes or timeout threshold is reached. This is essential for interactive applications like text editors (e.g., Vim) or curses-based interfaces, which require fine-grained control over single keypresses to trigger immediate UI updates.
Signals and Escaping
Beyond character buffering, the line discipline is responsible for intercepting specific control sequences and translating them into process signals. This is why pressing Ctrl+C triggers a SIGINT, or Ctrl+Z triggers a SIGTSTP. The line discipline inspects incoming bytes against a configured table of special characters and, upon a match, immediately sends the corresponding signal to the foreground process group associated with the terminal.
- Echoing: The ldisc manages automatic echoing of input characters back to the display, configurable through the ECHO flag.
- Flow Control: Characters like Ctrl+S (XOFF) and Ctrl+Q (XON) are intercepted here to pause and resume transmission, managing hardware-level buffers.
- Input Translation: The ldisc can map carriage returns to newlines or expand tabs to spaces before the application ever receives the byte stream.
Engineering Trade-offs
While the line discipline provides a convenient abstraction, it introduces latency. For high-performance interactive applications, the overhead of kernel processing and mode switching between canonical and non-canonical states can become a consideration. Understanding the N_TTY line discipline is crucial for developers building custom shells or terminal emulators, as misconfiguring these flags often leads to input lag, dropped signals, or characters appearing out of sequence.
The line discipline remains one of the oldest yet most critical components of the POSIX standard, effectively decoupling terminal hardware from software applications. By managing input buffering, signal generation, and echo control, it ensures that terminal-based software remains portable and performant across the vast ecosystem of Unix-like systems.