The POSIX terminal interface is the generalized abstraction, comprising both an
application programming interface
An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how t ...
for programs, and a set of behavioural expectations for users of a
terminal
Terminal may refer to:
Computing Hardware
* Terminal (electronics), a device for joining electrical circuits together
* Terminal (telecommunication), a device communicating over a line
* Computer terminal, a set of primary input and output dev ...
, as defined by the
POSIX
The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming interf ...
standard and the
Single Unix Specification. It is a historical development from the terminal interfaces of BSD version 4 and
Seventh Edition Unix
Seventh Edition Unix, also called Version 7 Unix, Version 7 or just V7, was an important early release of the Unix operating system. V7, released in 1979, was the last Bell Laboratories release to see widespread distribution before the commercial ...
.
General underlying concepts
Hardware
A multiplicity of I/O devices are regarded as "terminals" in Unix systems. These include:
*
serial device
Serial may refer to:
Arts, entertainment, and media The presentation of works in sequential segments
* Serial (literature), serialised literature in print
* Serial (publishing), periodical publications and newspapers
* Serial (radio and televisi ...
s connected by a
serial port
In computing, a serial port is a serial communication interface through which information transfers in or out sequentially one bit at a time. This is in contrast to a parallel port, which communicates multiple bits simultaneously in parallel. ...
such as
printer
Printer may refer to:
Technology
* Printer (publishing), a person or a company
* Printer (computing), a hardware device
* Optical printer for motion picture films
People
* Nariman Printer (fl. c. 1940), Indian journalist and activist
* James ...
s/
teleprinter
A teleprinter (teletypewriter, teletype or TTY) is an electromechanical device that can be used to send and receive typed messages through various communications channels, in both point-to-point and point-to-multipoint configurations. Initia ...
s,
teletypewriter
A teleprinter (teletypewriter, teletype or TTY) is an electromechanical device that can be used to send and receive typed messages through various communications channels, in both point-to-point (telecommunications), point-to-point and point- ...
s,
modem
A modulator-demodulator or modem is a computer hardware device that converts data from a digital format into a format suitable for an analog transmission medium such as telephone or radio. A modem transmits data by Modulation#Digital modulati ...
s supporting ''remote''
terminal
Terminal may refer to:
Computing Hardware
* Terminal (electronics), a device for joining electrical circuits together
* Terminal (telecommunication), a device communicating over a line
* Computer terminal, a set of primary input and output dev ...
s via
dial-up access
Dial-up Internet access is a form of Internet access that uses the facilities of the public switched telephone network (PSTN) to establish a connection to an Internet service provider (ISP) by dialing a telephone number on a conventional telepho ...
, and directly connected ''local'' terminals
*
display adapter
A graphics card (also called a video card, display card, graphics adapter, VGA card/VGA, video adapter, display adapter, or mistakenly GPU) is an expansion card which generates a feed of output images to a display device, such as a computer mo ...
and
keyboard
Keyboard may refer to:
Text input
* Keyboard, part of a typewriter
* Computer keyboard
** Keyboard layout, the software control of computer keyboards and their mapping
** Keyboard technology, computer keyboard hardware and firmware
Music
* Musi ...
hardware directly incorporated into the system unit, taken together to form a local "console", which may be presented to users and to programs as a single CRT terminal or as multiple
virtual terminal
In open systems, a virtual terminal (VT) is an application service that:
# Allows host terminals on a multi-user network to interact with other hosts regardless of terminal type and characteristics,
# Allows remote log-on by local area network ...
s
* software
terminal emulator
A terminal emulator, or terminal application, is a computer program that emulates a video terminal within some other display architecture. Though typically synonymous with a shell or text terminal, the term ''terminal'' covers all remote termin ...
s, such as the
xterm
In computing, xterm is the standard terminal emulator for the X Window System. It allows users to run programs which require a command-line interface.
If no particular program is specified, xterm runs the user's shell. An X display can show ...
,
Konsole
Konsole is a free and open-source terminal emulator graphical application which is part of KDE Applications and ships with the KDE desktop environment. Konsole was originally written by Lars Doelle. It ls licensed under the GPL-2.0-or-later and t ...
,
GNOME Terminal
GNOME Terminal is a terminal emulator for the GNOME desktop environment written by Havoc Pennington and others. Terminal emulators allow users to access a UNIX shell while remaining on their graphical desktop.
Features
GNOME Terminal (gnome-term ...
, and
Terminal
Terminal may refer to:
Computing Hardware
* Terminal (electronics), a device for joining electrical circuits together
* Terminal (telecommunication), a device communicating over a line
* Computer terminal, a set of primary input and output dev ...
programs, and network servers such as the
rlogin
The Berkeley r-commands are a suite of computer programs designed to enable users of one Unix system to log in or issue commands to another Unix computer via TCP/IP computer network. The r-commands were developed in 1982 by the Computer Systems ...
daemon and the
SSH
The Secure Shell Protocol (SSH) is a cryptographic network protocol for operating network services securely over an unsecured network. Its most notable applications are remote login and command-line execution.
SSH applications are based on a ...
daemon, which make use of
pseudoterminal
In some operating systems, including Unix and Linux, a pseudoterminal, pseudotty, or PTY is a pair of pseudo-device endpoints (files) which establish asynchronous, bidirectional communication ( IPC) channel (with two ports) between two or more pr ...
s
Terminal intelligence and capabilities
Intelligence: terminals are dumb, not intelligent
Unlike its mainframe and minicomputer contemporaries, the original Unix system was developed solely for ''dumb'' terminals, and that remains the case today. A terminal is a character-oriented device, comprising streams of characters received from and sent to the device. Although the streams of characters are structured, incorporating
control character
In computing and telecommunication, a control Character (computing), character or non-printing character (NPC) is a code point (a number) in a character encoding, character set, that does not represent a written symbol. They are used as in-band ...
s,
escape code
In computer science, an escape sequence is a combination of characters that has a meaning other than the literal characters contained therein; it is marked by one or more preceding (and possibly terminating) characters.
Examples
* In C and man ...
s, and special characters, the I/O protocol is not structured as would be the I/O protocol of ''smart'', or ''
intelligent'', terminals. There are no field format specifications. There's no block transmission of entire screens (input forms) of input data.
By contrast mainframes and minicomputers in closed architectures commonly use
Block-oriented terminal
A computer terminal is an electronic or electromechanical hardware device that can be used for entering data into, and transcribing data from, a computer or a computing system. The teletype was an example of an early-day hard-copy terminal and ...
s.
Capabilities: terminfo, termcap, curses, et al.
The "capabilities" of a terminal comprise various dumb terminal features that are above and beyond what is available from a pure teletypewriter, which programs can make use of. They (mainly) comprise escape codes that can be sent to or received from the terminal. The escape codes sent to the terminal perform various functions that a CRT terminal (or software terminal emulator) is capable of that a teletypewriter is not, such as moving the terminal's cursor to positions on the screen, clearing and scrolling all or parts of the screen, turning on and off attached printer devices, programmable function keys, changing display colours and attributes (such as
reverse video
Reverse video (or invert video or inverse video or reverse screen) is a computer display technique whereby the background and text color values are inverted. On older computers, displays were usually designed to display text on a black backgroun ...
), and setting display title strings. The escape codes received from the terminal signify things such as
function key
A function key is a key on a computer or terminal keyboard that can be programmed so as to cause an operating system command interpreter or application program to perform certain actions, a form of soft key. On some keyboards/computers, function ...
,
arrow key
Arrow keys or cursor movement keys are buttons on a computer keyboard that are either programmed or designated to move the cursor in a specified direction.
The term "cursor movement key" is distinct from "arrow key" in that the former term may ...
, and other special
keystroke
In programming and software design, an event is an action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Computer events can be generated or triggered ...
s (
home key
A home, or domicile, is a space used as a permanent or semi-permanent residence for one or many humans, and sometimes various companion animals. It is a fully or semi sheltered space and can have both interior and exterior aspects to it. H ...
,
end key
The key is a key commonly found on desktop and laptop keyboards. The key has the opposite effect of the Home key. In some limited-size keyboards where the key is missing the same functionality can be reached via the key combination of or Con ...
,
help key
A Help key, found in the shape of a dedicated key explicitly labeled , or as another key, typically one of the function keys, on a computer keyboard, is a key which, when pressed, produces information on the screen/display to aid the user in their ...
,
PgUp key,
PgDn key,
insert key
The Insert key (often abbreviated Ins) is a key commonly found on computer keyboards.
It is primarily used to switch between the two text-entering modes on a personal computer (PC) or word processor:
* overtype mode, in which the cursor, when ...
,
delete key
The delete key is a key on most computer keyboards which is typically used to delete either (in text mode) the character ahead of or beneath the cursor, or (in GUI mode) the currently-selected object. The key is sometimes referred to as the "for ...
, and so forth).
These capabilities are encoded in databases that are configured by a system administrator and accessed from programs via the
terminfo
Terminfo is a library and database that enables programs to use display terminals in a device-independent manner. Mary Ann Horton implemented the first terminfo library in 1981–1982 as an improvement over termcap. The improvements include
* fast ...
library (which supersedes the older
termcap
Termcap (''terminal capability'') is a software library and database used on Unix-like computers. It enables programs to use display computer terminals in a device-independent manner, which greatly simplifies the process of writing portable text m ...
library), upon which in turn are built libraries such as the
curses
A curse (also called an imprecation, malediction, execration, malison, anathema, or commination) is any expressed wish that some form of adversity or misfortune will befall or attach to one or more persons, a place, or an object. In particular, ...
and
ncurses
ncurses (new curses) is a programming library providing an application programming interface (API) that allows the programmer to write text-based user interfaces (TUI) in a terminal-independent manner. It is a toolkit for developing "GUI-like" ...
libraries. Application programs use the terminal capabilities to provide
textual user interface
In computing, text-based user interfaces (TUI) (alternately terminal user interfaces, to reflect a dependence upon the properties of computer terminals and not just text), is a retronym describing a type of user interface (UI) common as an ear ...
s with windows, dialogue boxes, buttons, labels, input fields, menus, and so forth.
Controlling environment variables: TERM
et al.
The particular set of capabilities for the terminal that a (terminal-aware) program's input and output uses is obtained from the database rather than hardwired into programs and libraries, and is controlled by the
TERM
environment variable
An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs. For example, a running process can query the value of the TEMP env ...
(and, optionally for the termcap and terminfo libraries, the
TERMCAP
and
TERMINFO
environment variables, respectively). This variable is set by whatever ''terminal monitor'' program spawns the programs that then use that terminal for its input and output, or sometimes explicitly. For example:
* The
getty program (or equivalent) sets the
TERM
environment variable according to a system database (variously
inittab
In Unix-based computer operating systems, init (short for ''initialization'') is the first process started during booting of the computer system. Init is a daemon process that continues running until the system is shut down. It is the direct ...
or the configuration files for the
ttymon or
launchd
launchd is an init and operating system service management daemon created by Apple Inc. as part of macOS to replace its BSD-style init and SystemStarter. There have been efforts to port launchd to FreeBSD and derived systems.
Components
Th ...
programs) defining what local terminals are attached to what serial ports and what terminal types are provided by local virtual terminals or the local system console.
* A dial-up user on a remote terminal is not using the type of terminal that the system commonly expects on that dial-up line, and so manually sets the
TERM
environment variable immediately after login to the correct type. (More usually, the terminal type set by the getty program for the dial-up line, that the system administrator has determined to be used most often by dial-up users with remote terminals, matches the one used by the dial-up user and that user has no need to override the terminal type.)
* The
SSH
The Secure Shell Protocol (SSH) is a cryptographic network protocol for operating network services securely over an unsecured network. Its most notable applications are remote login and command-line execution.
SSH applications are based on a ...
server daemon (or equivalent such as the
rlogin
The Berkeley r-commands are a suite of computer programs designed to enable users of one Unix system to log in or issue commands to another Unix computer via TCP/IP computer network. The r-commands were developed in 1982 by the Computer Systems ...
daemon) sets the
TERM
environment variable to the same terminal type as the SSH client.
* The software terminal emulator, using a pseudoterminal, sets the
TERM
environment variable to specify the type of terminal that it is emulating. Emulated terminals often do not exactly match real terminal hardware, and terminal emulators have type names dedicated for their use. The xterm program (by default) sets
xterm
as the terminal type, for example. The
GNU Screen
GNU Screen is a terminal multiplexer, a software application that can be used to multiplex several virtual consoles, allowing a user to access multiple separate login sessions inside a single terminal window, or detach and reattach sessions from ...
program sets
screen
as the terminal type.
Job control
Terminals provide job control facilities. Interactively, the user at the terminal can send control characters that suspend the currently running job, reverting to the interactive job control shell that spawned the job, and can run commands that place jobs in the "background" or that switch another, background, job into the foreground (unsuspending it if necessary).
Line disciplines
Strictly speaking, in Unixes a terminal device comprises the underlying ''tty device driver'', responsible for the physical control of the device hardware via I/O instructions and handling device interrupt requests for character input and output, and the ''line discipline''. A line discipline is independent of the actual device hardware, and the same line discipline can be used for a
terminal concentrator
Terminal may refer to:
Computing Hardware
* Terminal (electronics), a device for joining electrical circuits together
* Terminal (telecommunication), a device communicating over a line
* Computer terminal, a set of primary input and output devic ...
device responsible for multiple controlling terminals as for a pseudoterminal. In fact, the line discipline (or, in the case of BSD, AIX, and other systems, line ''disciplines'') are the same across all terminal devices. It is the line discipline that is responsible for local echo, line editing, processing of input modes, processing of output modes, and character mapping. All these things are independent of the actual hardware, dealing as they do in the simple abstractions provided by tty device drivers: transmit a character, receive a character, set various hardware states.
In
Seventh Edition Unix
Seventh Edition Unix, also called Version 7 Unix, Version 7 or just V7, was an important early release of the Unix operating system. V7, released in 1979, was the last Bell Laboratories release to see widespread distribution before the commercial ...
,
BSD
The Berkeley Software Distribution or Berkeley Standard Distribution (BSD) is a discontinued operating system based on Research Unix, developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berk ...
systems and derivatives including
macOS
macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
, and
Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
, each terminal device can be switched amongst multiple line disciplines. In the AT&T
STREAMS
A stream is a continuous body of water, body of surface water Current (stream), flowing within the stream bed, bed and bank (geography), banks of a channel (geography), channel. Depending on its location or certain characteristics, a stream ...
system, line disciplines are STREAMS modules that may be pushed onto and popped off a STREAMS I/O stack.
History
The POSIX terminal interface is derived from the terminal interfaces of various Unix systems.
Early Unixes: Seventh Edition Unix
The terminal interface provided by Unix 32V and Seventh Edition Unix, and also presented by BSD version 4 as the ''old terminal driver'', was a simple one, largely geared towards teletypewriters as terminals. Input was entered a line at a time, with the terminal driver in the operating system (and not the terminals themselves) providing simple line editing capabilities. A buffer was maintained by the kernel in which editing took place. Applications reading terminal input would receive the contents of the buffer only when the key was pressed on the terminal to end line editing. The key sent from the terminal to the system would erase ("kill") the entire current contents of the editing buffer, and would be normally displayed as an '' symbol followed by a newline sequence to move the print position to a fresh blank line. The key sent from the terminal to the system would erase the last character from the end of the editing buffer, and would be normally displayed as an '' symbol, which users would have to recognize as denoting a "rubout" of the preceding character (teletypewriters not being physically capable of erasing characters once they have been printed on the paper).
From a programming point of view, a terminal device had transmit and receive
baud rate
In telecommunication and electronics, baud (; symbol: Bd) is a common unit of measurement of symbol rate, which is one of the components that determine the speed of communication over a data channel.
It is the unit for symbol rate or modulati ...
s, "erase" and "kill" characters (that performed line editing, as explained), "interrupt" and "quit" characters (generating
signal
In signal processing, a signal is a function that conveys information about a phenomenon. Any quantity that can vary over space or time can be used as a signal to share messages between observers. The ''IEEE Transactions on Signal Processing'' ...
s to all of the processes for which the terminal was a controlling terminal), "start" and "stop" characters (used for
modem flow control), an "end of file" character (acting like a carriage return except discarded from the buffer by the
read()
system call and therefore potentially causing a zero-length result to be returned) and various ''basic mode flags'' determining whether
local echo was emulated by the kernel's terminal driver, whether modem flow control was enabled, the lengths of various output delays, mapping for the carriage return character, and the three input modes.
The three input modes were:
;line mode (also called "cooked" mode):
In line mode the line discipline performs all line editing functions and recognizes the "interrupt" and "quit" control characters and transforms them into signals sent to processes. Applications programs reading from the terminal receive entire lines, after line editing has been completed by the user pressing return.
;cbreak mode:
cbreak mode is one of two character-at-a-time modes. (
Stephen R. Bourne
Stephen Richard "Steve" Bourne (born 7 January 1944) is an English computer scientist based in the United States for most of his career. He is well known as the author of the Bourne shell (sh), which is the foundation for the standard command-li ...
jokingly referred to it as a "half-cooked" and therefore "rare" mode.) The line discipline performs no line editing, and the control sequences for line editing functions are treated as normal character input. Applications programs reading from the terminal receive characters immediately, as soon as they are available in the
input queue
In computer science, an input queue is a collection of processes in storage that are waiting to be brought into memory to run a program. Input queues are mainly used in Operating System Scheduling which is a technique for distributing resources ...
to be read. However, the "interrupt" and "quit" control characters, as well as modem flow control characters, are still handled specially and stripped from the input stream.
;raw mode:raw mode is the other of the two character-at-a-time modes. The line discipline performs no line editing, and the control sequences for both line editing functions and the various special characters ("interrupt", "quit", and flow control) are treated as normal character input. Applications programs reading from the terminal receive characters immediately, and receive the entire character stream unaltered, just as it came from the terminal device itself.
The programmatic interface for querying and modifying all of these modes and control characters was the
ioctl()
system call. (This replaced the
stty()
and
gtty()
system calls of Sixth Edition Unix.) Although the "erase" and "kill" characters were modifiable from their defaults of and , for many years they were the pre-set defaults in the terminal device drivers, and on many Unix systems, which only altered terminal device settings as part of the login process, in system login scripts that ran ''after'' the user had entered username and password, any mistakes at the login and password prompts had to be corrected using the historical editing key characters inherited from teletypewriter terminals.
BSD: the advent of job control
With the BSD Unixes came
job control, and a ''new terminal driver'' with extended capabilities. These extensions comprised additional (again programmatically modifiable) special characters:
* The "suspend" and "delayed suspend" characters (by default and — ASCII
SUB
and
EM
) caused the generation of a new
SIGTSTP
In Unix and Unix-like operating systems, job control refers to control of jobs by a shell, especially interactively, where a "job" is a shell's representation for a process group. Basic job control features are the suspending, resuming, or termina ...
signal to processes in the terminal's controlling process group.
* The "word erase", "literal next", and "reprint" characters (by default , , and — ASCII
ETB
,
SYN
, and
DC2
) performed additional line editing functions. "word erase" erased the last word at the end of the line editing buffer. "literal next" allowed any special character to be entered into the line editing buffer (a function available, somewhat inconveniently, in Seventh Edition Unix via the backslash character). "reprint" caused the line discipline to reprint the current contents of the line editing buffer on a new line (useful for when another, background, process had generated output that had intermingled with line editing).
The programmatic interface for querying and modifying all of these extra modes and control characters was still the
ioctl()
system call, which its creators described as a "rather cluttered interface". All of the original Seventh Edition Unix functionality was retained, and the new functionality was added via additional
ioctl()
operation codes, resulting in a programmatic interface that had clearly grown, and that presented some duplication of functionality.
System III and System V
System III introduced a new programming interface that combined Seventh Edition's separate
ioctl()
operations to get and set flags and to get and set control characters into calls that used a
termio
structure to hold both flags and control characters and that could get them in a single operation and set them in another single operation. It also split some of the flags from the Seventh Edition interface into multiple separate flags, and added some additional capabilities, although it did not support job control or the cooked-mode enhancements of 4BSD.
For example, it replaced the "cooked", "cbreak", and "raw" modes of Seventh Edition with different abstractions. The recognition of signal-generating characters is independent of input mode, and there are only the two input modes: canonical and non-canonical. (This allows a terminal input mode not present in Seventh Edition and BSD: canonical mode with signal generation disabled.)
System III's successors, including
System V
Unix System V (pronounced: "System Five") is one of the first commercial versions of the Unix operating system. It was originally developed by AT&T and first released in 1983. Four major versions of System V were released, numbered 1, 2, 3, an ...
, used the same interface.
POSIX: Consolidation and abstraction
One of the major problems that the POSIX standard addressed with its definition of a general terminal interface was the plethora of programmatic interfaces. Although by the time of the standard the behaviour of terminals was fairly uniform from system to system, most Unixes having adopted the notions of line disciplines and the BSD job control capabilities, the programmatic interface to terminals via the
ioctl()
system call was a mess. Different Unixes supplied different
ioctl()
operations, with different (symbolic) names, and different flags. Portable source code had to contain a significant amount of conditional compilation to accommodate the differences across software platforms, even though they were all notionally Unix.
The POSIX standard replaces the
ioctl()
system entirely, with a set of library functions (which, of course, may be ''implemented'' under the covers via platform-specific
ioctl()
operations) with standardized names and parameters. The
termio
data structure of System V Unix was used as a template for the POSIX
termios
data structure, whose fields were largely unchanged except that they now used alias data types for specifying the fields, allowing them to be easily ported across multiple processor architectures by implementors, rather than explicitly requiring the
unsigned short
and
char
data types of the C and C++ programming languages (which might be inconvenient sizes on some processor architectures).
POSIX also introduced support for job control, with the
termios
structure containing suspend and delayed-suspend characters in addition to the control characters supported by System III and System V. It did not add any of the cooked-mode extensions from BSD, although
SunOS
SunOS is a Unix-branded operating system developed by Sun Microsystems for their workstation and server computer systems. The ''SunOS'' name is usually only used to refer to versions 1.0 to 4.1.4, which were based on BSD, while versions 5.0 and l ...
4.x,
System V Release 4
Unix System V (pronounced: "System Five") is one of the first commercial versions of the Unix operating system. It was originally developed by AT&T and first released in 1983. Four major versions of System V were released, numbered 1, 2, 3, an ...
,
Solaris
Solaris may refer to:
Arts and entertainment Literature, television and film
* ''Solaris'' (novel), a 1961 science fiction novel by Stanisław Lem
** ''Solaris'' (1968 film), directed by Boris Nirenburg
** ''Solaris'' (1972 film), directed by ...
,
HP-UX
HP-UX (from "Hewlett Packard Unix") is Hewlett Packard Enterprise's proprietary implementation of the Unix operating system, based on Unix System V (initially System III) and first released in 1984. Current versions support HPE Integrity Ser ...
,
AIX
Aix or AIX may refer to:
Computing
* AIX, a line of IBM computer operating systems
*An Alternate Index, for a Virtual Storage Access Method Key Sequenced Data Set
*Athens Internet Exchange, a European Internet exchange point
Places Belgium
...
, newer BSDs,
macOS
macOS (; previously OS X and originally Mac OS X) is a Unix operating system developed and marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers. Within the market of desktop and lapt ...
, and
Linux
Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
have implemented them as extensions to
termios
.
What the standard defines
Controlling terminals and process groups
Each
process
A process is a series or set of activities that interact to produce a result; it may occur once-only or be recurrent or periodic.
Things called a process include:
Business and management
*Business process, activities that produce a specific se ...
in the system has either a single ''controlling terminal'', or no controlling terminal at all. A process inherits its controlling terminal from its parent, and the only operations upon a process are acquiring a controlling terminal, by a process that has no controlling terminal, and relinquishing it, by a process that has a controlling terminal.
No portable way of acquiring a controlling terminal is defined, the method being implementation defined. The standard defines the
O_NOCTTY
flag for the
open()
system call, which is the way of ''preventing'' what is otherwise the conventional way of acquiring a controlling terminal (a process with no controlling terminal
open()
s a terminal device file that isn't already the controlling terminal for some other process, without specifying the
O_NOCTTY
flag) but leaves its conventional semantics optional.
Each process also is a member of a process group. Each terminal device records a process group that is termed its ''foreground process group''. The process groups control terminal access and signal delivery. Signals generated at the terminal are sent to all processes that are members of the terminal's foreground process group.
read()
and
write()
I/O operations on a terminal by a process that is not a member of the terminal's foreground process group will and may optionally (respectively) cause signals (
SIGTTIN
In Unix and Unix-like operating systems, job control refers to control of jobs by a shell, especially interactively, where a "job" is a shell's representation for a process group. Basic job control features are the suspending, resuming, or termina ...
and
SIGTTOU
In Unix and Unix-like operating systems, job control refers to control of jobs by a shell, especially interactively, where a "job" is a shell's representation for a process group. Basic job control features are the suspending, resuming, or termina ...
respectively) to be sent to the invoking process. Various terminal-mode-altering library functions have the same behaviour as
write()
, except that they always generate the signals, even if that functionality is turned off for
write()
itself.
The termios
data structure
The data structure used by all of the terminal library calls is the
termios
structure, whose C and C++ programming language definition is as follows:
struct termios ;
The order of the fields within the
termios
structure is not defined, and implementations are allowed to add non-standard fields. Indeed, implementations have to add non-standard fields for recording input and output baud rates. These are recorded in the structure, in an implementation-defined form, and accessed via accessor functions, rather than by direct manipulation of the field values, as is the case for the standardized structure fields.
The data type aliases
tcflag_t
and
cc_t
, as well as the symbolic constant
NCCS
and symbolic constants for the various mode flags, control character names, and baud rates, are all defined in a standard header
termios.h
. (This is not to be confused with the similarly named header
termio.h
from System III and System V, which defines a similar
termio
structure and a lot of similarly named symbolic constants. This interface is specific to System III and System V, and code that uses it will not necessarily be portable to other systems.)
The structure's fields are (in summary, for details see the main article):
;
c_iflag
:input mode flags for controlling input parity, input newline translation, modem
flow control,
8-bit clean
''8-bit clean'' is an attribute of computer systems, communication channels, and other devices and software, that handle 8-bit character encodings correctly. Such encoding include the ISO 8859 series and the UTF-8 encoding of Unicode.
History
...
liness, and response to a (serial port's)
"break" condition
;
c_oflag
:output mode flags for controlling implementation-defined output postprocessing, output newline translation, and output delays after various control characters have been sent
;
c_cflag
:terminal hardware control flags for controlling the actual terminal device rather than the line discipline: the number of bits in a character, parity type, hangup control, and serial line flow control
;
c_lflag
:local control flags for controlling the line discipline rather than the terminal hardware: canonical mode, echo modes, signal-generation character recognition and handling, and enabling the generation of the
SIGTTOU
signal by the
write()
system call
The library functions are (in summary, for details see the main article):
;
tcgetattr()
:query a terminal device's current attribute settings into a
termios
structure
;
tcsetattr()
:set a terminal device's current attribute settings from a
termios
structure, optionally waiting for queued output to drain and flushing queued input
;
cfgetispeed()
:query the input baud rate from the implementation-defined fields in a
termios
structure
;
cfgetospeed()
:query the output baud rate from the implementation-defined fields in a
termios
structure
;
cfsetispeed()
:set the input baud rate in the implementation-defined fields in a
termios
structure
;
cfsetospeed()
:set the output baud rate in the implementation-defined fields in a
termios
structure
;
tcsendbreak()
:send a modem "break" signal on a serial device terminal
;
tcdrain()
:wait for queued output to drain
;
tcflush()
:discard queued input
;
tcflow()
:change flow control
;
tcgetpgrp()
:query the terminal's foreground process group
;
tcsetpgrp()
:set the terminal's foreground process group
Special characters
The
c_cc[]
array member of the
termios
data structure specifies all of the (programmatically modifiable) special characters. The indexes into the array are symbolic constants, one for each special character type, as in the table at right. (Two further entries in the array are relevant to non-canonical mode input processing and are discussed below.)
Non-programmatically modifiable special characters are ''linefeed'' (ASCII
LF
) and ''carriage return'' (ASCII
CR
).
Input processing
Input processing determines the behaviour of the
read()
system call on a terminal device and the line editing and signal-generation characteristics of the line discipline. Unlike the case of Seventh Edition Unix and BSD version 4, and like the case of System III and System V, line editing operates in one of just two modes: canonical mode and non-canonical mode. The basic difference between them is when, from the point of view of the blocking/non-blocking requirements of the
read()
system call (specified with the
O_NONBLOCK
flag on the
file descriptor
In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier (handle) for a file or other input/output resource, such as a pipe or network socket.
File descriptors typically have ...
via
open()
or
fcntl()
), data "are available for reading".
Canonical mode processing
In canonical mode, data are accumulated in a line editing buffer, and do not become "available for reading" until line editing has been terminated by the user (at the terminal) sending a ''line delimiter character''. Line delimiter characters are special characters, and they are ''end of file'', ''end of line'', and ''linefeed'' (ASCII
LF
). The former two are settable programmatically, whilst the latter is fixed. The latter two are included in the line editing buffer, whilst the former one is not.
More strictly, zero or more lines are accumulated in the line editing buffer, separated by line delimiters (which may or may not be discarded once
read()
comes around to reading them), and line editing operates upon the part of the line editing buffer that follows the last (if any) line delimiter in the buffer. So, for example, the "erase" character (whatever that has been programmed to be) will erase the last character in the line buffer only up to (but not including) a preceding line delimiter.
Non-canonical mode processing
In non-canonical mode, data are accumulated in a buffer (which may or may not be the line editing buffer — some implementations having separate "processed input" and "raw input" queues) and become "available for reading" according to the values of two input control parameters, the
c_cc[MIN]
and
c_cc[TIME]
members of the
termios
data structure. Both are unsigned quantities (because
cc_t
is required to be an alias for an unsigned type). The former specifies a minimum number of characters, and the latter specifies a timeout in tenths of a second. There are four possibilities:
;
c_cc[TIME]
and
c_cc[MIN]
are both zero
:In this case, the data in the buffer are "available for reading" immediately, and
read()
returns immediately with whatever data are in the buffer (potentially returning zero if there are zero data available).
;
c_cc[TIME]
is non-zero and
c_cc[MIN]
is zero
:In this case, the data in the buffer are "available for reading" after the specified timeout has elapsed, the timer being triggered by the start of the
read()
system call, or if a single character is received. In other words,
read()
waits for a maximum specified total time, and may return zero data, and returns any data as soon as they are received.
;
c_cc[TIME]
is zero and
c_cc[MIN]
is non-zero
:In this case, the data in the buffer are "available for reading" after the specified number of characters have been received in the buffer. In other words,
read()
waits for a minimum amount of data (which may be larger than what the caller is prepared to read in the system call), will not return zero data, and may wait indefinitely.
;
c_cc[TIME]
and
c_cc[MIN]
are both non-zero
:In this case, the data in the buffer are "available for reading" after the specified number of characters have been received in the buffer or the timeout has expired since the last character was entered. There is no timeout for the very first character. In other words,
read()
waits for a minimum amount of data (which may be larger than what the caller is prepared to read in the system call), will not return zero data, may wait indefinitely, but won't wait longer than the specified timeout if at least one character is in the buffer to be read.
Output processing
Output processing is largely unchanged from its System III/System V roots. Output mode control flags determine various options:
*
Carriage return
A carriage return, sometimes known as a cartridge return and often shortened to CR, or return, is a control character or mechanism used to reset a device's position to the beginning of a line of text. It is closely associated with the line feed a ...
s may be inserted before each linefeed character, to translate Unix newline semantics to the ASCII semantics that many terminals expect.
*Terminals may be given time to exercise various control codes that would (on a teletypewriter or similar) result in physical movements of the carriage that may take significant (from the computer's point of view) amounts of time, such as backspaces, horizontal tabs, carriage returns, form feeds, and line feeds.
Notes
Sources
*
*
*
*
*
*
*
Further reading
*
* {{cite book,
chapter=Terminal I/O,
title=POSIX programmer's guide: writing portable UNIX programs with the POSIX.1 standard,
series=Computer Science Series,
first=Donald A.,
last=Lewine,
publisher=O'Reilly Media, Inc.,
year=1991,
isbn=978-0-937175-73-6,
url=https://archive.org/details/posixprogrammers00lewi
Computer terminals
POSIX