NAME
tty - General terminal interface
SYNOPSIS
#include <sys/termios.h>
DESCRIPTION
tty is the general interface for terminal devices. This
interface supplies all the functionality needed for I/O over
console serial lines, workstation screens, keyboards, and
other terminal devices. It consists of the special file
dev/tty and terminal drivers used for conversational comput-
ing.
Much of the terminal interface's performance is governed by
the settings of a terminal's termios structure in the
termios.h file. This structure provides definitions for
terminal input and output processing, control and local
modes, and so on.
Line Disciplines
OSF/1 provides the STREAMS module ldterm for controlling
terminal I/O lines. This line discipline performs most of
the functions defined by the termio interface for session
management and character pocessing, but not some low-level
device control. Other line disciplines, such as those for
use with network communications lines, can be substituted
for ldterm. These line disciplines, however, must be
STREAMS-based and POSIX-compliant.
Users switch line disciplines by using the strchg command or
STREAMS ioctl call with the I_PUSH command.
The Controlling Terminal
OSF/1 supports the concept of a controlling terminal. Any
process in the system can have a controlling terminal asso-
ciated with it. Certain events, such as the delivery of
keyboard generated signals (for example, interrupt, quit,
suspend), affect all the processes in the process group
associated with the controlling terminal. The controlling
terminal also determines the physical device that is
accessed when the indirect device /dev/tty is opened.
In earlier versions of UNIX systems, a controlling terminal
was implicitly assigned to a process if, at the time an open
was done on the terminal, the terminal was not the control-
ling terminal for any process, and if the process doing the
open did not have a controlling terminal. In OSF/1, in
accordance with POSIX 1003.1, a process must be a session
leader to allocate a controlling terminal. In addition, the
allocation is now done explicitly with a call to ioctl().
(This implies that the O_NOCTTY flag to the open() function
is ignored.) The following example illustrates the correct
sequence for obtaining a controlling tty (no error checking
is shown). This code fragment calls the setsid() function
to make the current process the group and session leader,
and to remove any controlling tty that the process may
already have. It then opens the console device and attaches
it to the current session as the controlling terminal. Note
that the process must not already be a session or process
group leader, and the console must not already be the con-
trolling tty of any other session.
(void)setsid(); /* become session leader and */
/* lose controlling tty */
fd = open("/dev/console", O_RDWR);
(void)ioctl(fd,TIOCSCTTY,0);
A process can remove the association it has with its con-
trolling terminal by opening the /dev/tty file and issuing
the following call:
ioctl(fd, TIOCNOTTY, 0);
For example:
fd = open("/dev/tty", O_RDWR);
if (fd > = 0) {
ioctl(fd,TIOCNOTTY,0);
close(fd);
}
When a control terminal file is closed, pending input is
removed, and pending output is sent to the receiving device.
When a terminal file is opened, the process blocks until a
carrier signal is detected. If the open() function is
called with the O_NONBLOCK flag set, however, the process
does not wait. Instead, the first read() or write() call
will wait for carrier to be established. If the CLOCAL mode
is set in the termios structure, the driver assumes that
modem control is not in effect, and open(), read(), and
write() therefore proceed without waiting for a carrier sig-
nal to be established.
Process Groups
In OSF/1, each process belongs to a process group with a
specific process group ID. Each process belongs to the pro-
cess group of its creating process. This enables related
processes to be signalled. Process group IDs are unique
identifiers that cannot be used for other system process
groups until the original process group is disbanded. Each
process group also has a group leader process. A process
group leader has the same process ID as its process group.
Each process group belongs to a session. Each process in
the process group also belongs to the process group's ses-
sion. A process which is not the process group leader can
create its own session and process group with a call to the
setsid() function. That calling process then becomes the
session leader of the new session and of the new process
group. The new session has no controlling terminal until
the session leader assigns one to it. The calling process's
ID is assigned to the new process group. With the setpgid()
function, other processes can be added to a process group.
A controlling terminal can have a distinguished process
group associated with it known as the foreground process
group. The terminal's foreground process group is the one
that receives signals generated by the INTR, QUIT, and SUSP
special control characters. Certain operations on the ter-
minal are also restricted to processes in the terminal's
foreground process group (see "Terminal Access Control"). A
terminal's foreground process group may be changed by cal-
ling the tcsetpgrp() function. A terminal's current fore-
ground process group may be obtained by calling the
tcgetpgrp() function.
Input Processing Modes
The terminal drivers have two major modes, characterized by
the kind of processing that takes place on the input charac-
ters:
Canonical If a terminal is in canonical mode, input is col-
lected and processed one line at a time. Lines
are terminated by a newline (\n), End-of-File
(EOF), or End-of-Line (EOL) character. A read
request is not returned until the line has been
terminated, or a signal has been received. The
maximum number of bytes of unread input allowed on
an input terminal is 255 bytes. If the maximum
number of unread bytes exceeds 255 bytes, the
behavior of the driver depends on the setting of
the IMAXBEL input flag (see "Input Editing").
Erase and kill processing is performed on input
that has not been terminated by one of the line
termination characters. Erase processing removes
the last character in the line, kill processing
removes the whole line.
Noncanonical
This mode eliminates erase and kill processing,
making input characters available to the user
program as they are typed. Input is not processed
into lines. The received bytes are processed
according to the MIN and TIME elements of the c_cc
array in the termios structure.
MIN MIN is the minimum number of bytes the
terminal can receive in noncanonical
mode before a read is considered suc-
cessful.
TIME TIME, measured in 0.1 second granular-
ity, times out sporadic input.
These cases are summarized as follows:
MIN>0, TIME>0
In this case, TIME is an interbyte timer
that is activated after the first byte
of the input line is received, and reset
after each byte is received. The read
operation is a success if MIN bytes are
read before TIME runs out. If TIME runs
out before MIN bytes have been received,
the characters that were received are
returned.
MIN>0, TIME=0
In this case, only MIN is used. A
queued read() waits until MIN bytes are
received, or a signal is received.
MIN=0, TIME>0
In this case, TIME is used as a read
timer that starts when a read() call is
made. The read() call is finished when
one byte is read, or when TIME runs out.
MIN=0, TIME=0
In this case, either the number of
requested bytes or the number of
currently available bytes is returned,
depending on which is the lesser number.
The read() function returns a zero if no
data was read.
Canonical mode is entered by setting the ICANON flag of the
c_lflag field in the in the terminal's termios structure.
Other input processing is performed according to the other
flags set in the c_iflag and c_lflag fields.
Input Editing
A terminal ordinarily operates in full-duplex mode. Charac-
ters may be typed at any time, even while output is occur-
ring. Characters are only lost when:
o The system's character input buffers become completely
choked, which is rare.
o The user has accumulated the maximum allowed number of
input characters (MAX_INPUT) that have not yet been
read by some program. Currently this limit is 255
characters. When this limit is reached, the terminal
driver refuses to accept any further input and rings
the terminal bell if IMAXBEL is set in the c_iflag
field, or throws away all input and output without
notice if this flag is not set.
Input characters are normally accepted in either even or odd
parity with the parity bit being stripped off before the
character is given to the program. The ISTRIP mask of the
c_iflag field controls whether the parity bit is stripped
(ISTRIP set) or not stripped (ISTRIP not set). By setting
the PARENB flag in the c_cflag field, and either setting
(not setting) the PARODD flag, it is possible to have input
characters with EVEN (ODD) parity discarded or marked (see
"Input Modes").
In all of the line disciplines, it is possible to simulate
terminal input using the TIOCSTI ioctl, which takes, as its
third argument, the address of a character. The system pre-
tends that this character was typed on the argument termi-
nal, which must be the control terminal for the process,
unless the process has superuser privileges.
Input characters are normally echoed by putting them in an
output queue as they arrive. This may be disabled by clear-
ing the ECHO bit in the c_lflag word using the tcsetattr()
call or the TIOCSETA, TIOCSETAW, or TIOCSETAF ioctls.
In canonical mode, terminal input is processed in units of
lines. A program attempting to read will normally be
suspended until an entire line has been received (but see
the description of SIGTTIN in "Terminal Access Control").
No matter how many characters are requested in the read
call, at most one line will be returned. It is not, how-
ever, necessary to read a whole line at once; any number of
characters may be requested in a read, even one, without
losing information. In read() requests, the O_NONBLOCK flag
affects the read() operation behavior.
If O_NONBLOCK is not set, a read() request is blocked until
data or a signal has been received. If the O_NONBLOCK flag
is set, the read() request is not blocked, and one of the
following situations holds:
o Some data may have been typed, but there may or may not
be enough data to satisfy the entire read request. In
either case, the read() function returns the data
available, returning the number of bytes of data it
read.
o If there is no data for the read operation, the read()
returns a -1 with an error of EAGAIN.
During input, line editing is normally done with the erase
special control character (VERASE) logically erasing the
last character typed and the kill special control character
(VKILL) logically erasing the entire current input line.
These characters never erase beyond the beginning of the
current input line or an EOF (End-of-File). These charac-
ters, along with the other special control characters, may
be entered literally by preceding them with the literal-next
character (VLNEXT - default ^V).
The drivers normally treat either a newline character
(`\n'), End-of-File character (EOF), or End-of-Line charac-
ter (EOL) as terminating an input line, echoing a return and
a line feed. If the ICRNL character bit is set in the
c_iflag word then carriage returns are translated to new-
line characters on input, and are normally echoed as car-
riage return-linefeed sequences. If ICRNL is not set, this
processing for carriage return is disabled, and it is simply
echoed as a return, and does not terminate cooked mode
input.
The POSIX terminal driver also provides two other editing
characters in normal mode. The word-erase character, nor-
mally <Ctrl-W>, is a c_cc structure special control charac-
ter VWERASE. This character erases the preceding word, but
not any spaces before it. For the purposes of <Ctrl-W>, a
word is defined as a sequence of nonblank characters, with
tabs counted as blanks. However, if the ALTWERASE flag is
set in the c_lflag word, then a word is considered to be any
sequence of alphanumerics or underscores bounded by charac-
ters that are not alphanumerics or underscores. Finally,
the reprint character, normally <Ctrl-R>, is a c_cc struc-
ture special control character VREPRINT. This character
retypes the pending input beginning on a new line. Retyping
occurs automatically in canonical mode if characters which
would normally be erased from the screen are fouled by pro-
gram output.
Input Modes
The termios structure has an input mode field c_iflag, which
controls basic terminal input characteristics. These
characteristics are masks that can be bitwise inclusive
ORed. The masks include:
BRKINT An interrupt is signalled on a break condition.
ICRNL All carriage returns are mapped to newline charac-
ters when input.
IGNBRK Break conditions are ignored.
IGNCR Carriage returns are ignored.
IGNPAR Characters with parity errors are ignored.
INLCR Newline characters are mapped to carriage returns
when input.
INPCK Parity checks are enabled on input.
ISTRIP The eighth bit (parity bit) is stripped on input
characters.
IXOFF Stop/start characters are sent for input flow con-
trol enabled.
IXON Stop/start characters are recognized for output
flow control.
IXANY Any char will restart output after stop.
IUCLC Map upper case to lower case on input.
PARMRK Parity errors are marked with a three character
sequence.
IMAXBEL
The bell is rung when the input queue fills.
The input mode mask bits can be combined for the following
results:
The setting of IGNBRK causes input break conditions to be
ignored. If IGNBRK is not set, but BRKINT is set, the break
condition has the same effect as if the VINTR control char-
acter had been typed. If neither IGNBRK nor BRKINT are set,
then the break condition is input as a single character
'\0'. If the PARMRK flag is set, then the input is read as
three characters, '\377', '\0', and '\0'.
The setting of IGNPAR causes a byte with a parity or framing
error, except for breaks, to be ignored (that is, dis-
carded). If IGNPAR is not set, but PARMRK is set, a byte
with parity or framing error, except for breaks, is passed
as the three characters '\377', '\0', and X, where X is the
character data received in error. If the ISTRIP flag is not
set, the valid character '\377' is passed as '\377', '377'.
If both PARMRK and IGNPAR are not set, framing or parity
errors, including breaks, are passed as the single character
'\0'.
The setting of INPCK enables input parity checking. If
input parity checking is not enabled (INPCK not set), then
characters with parity errors are simply passed through as
is. The enabling/disabling of input parity checking is
independent of the generation of parity on output.
Setting ISTRIP causes the eighth bit of the eight valid
input bits to be stripped before processing. If this mask
is not set, all eight bits are processed.
Setting INLCR causes a newline character to be read as a
carriage return character. If the IGNCR flag is also set,
the carriage return is ignored. If the IGNCR flag is not
set, INLCR works as described earlier.
The STOP character (normally <Ctrl-S>) suspends output and
the START character (normally <Ctrl-Q>) restarts output.
Setting IXON enables stop/start output control, in which the
START and STOP characters are not read, but rather perform
flow control functions. Extra stop characters typed when
output is already stopped have no effect, unless the start
and stop characters are made the same, in which case output
resumes. Disabling IXON causes the START and STOP charac-
ters to be read.
Setting IXOFF enables stop/start input control. When this
flag is set, the terminal device will be sent STOP charac-
ters to halt the transmission of data when the input queue
is in danger of overflowing (exceed MAX_INPUT). When enough
characters have been read to reduce the amount of data
queued to an acceptable level, a START character is sent to
the device to allow it to continue transmitting data. This
mode is useful when the terminal is actually another machine
that obeys those conventions.
Input Echoing and Redisplay
The terminal driver has several modes for handling the echo-
ing of terminal input, controlled by bits in the c_lflag
field of the termios structure.
Hardcopy Terminals
When a hardcopy terminal is in use, the ECHOPRT bit is nor-
mally set in the local flags word. Characters which are
logically erased are then printed out backwards preceded by
\ (backslash) and followed by a / (slash) in this mode.
Erasing Characters from a CRT
When a CRT terminal is in use, the ECHOE bit may be set to
cause input to be erased from the screen with a "backspace-
space-backspace" sequence when character or word deleting
sequences are used. The ECHOKE bit may be set as well,
causing the input to be erased in this manner on line kill
sequences as well.
Echoing of Control Characters
If the ECHOCTL bit is set in the local flags word, then non-
printing (control) characters are normally echoed as ^X (for
some X) rather than being echoed unmodified; DELETE is
echoed as ^?.
Output Processing
When one or more characters are written, they are actually
transmitted to the terminal as soon as previously written
characters have finished typing. (As noted above, input
characters are normally echoed by putting them in the output
queue as they arrive.) When a process produces characters
more rapidly than the terminal can accept them, it will be
suspended when its output queue exceeds some limit. When
the queue has drained down to some threshold the program is
resumed. Even parity is normally generated on output. If
the NOEOT bit is set in the c_oflag word of the termios
structure, the EOT character (<Ctrl-D>) is not transmitted,
to prevent terminals that respond to it from hanging up.
The terminal drivers provide necessary processing for canon-
ical and noncanonical mode output including delay generation
for certain special characters and parity generation.
Delays are available after backspaces (BSDLY), formfeeds
(FFDLY), carriage returns (CRDLY), tabs (TABDLY) and new-
lines (NLDLY). The driver will also optionally expand tabs
into spaces, where the tab stops are assumed to be set every
eight columns, and optionally convert newlines to carriage
returns followed by newline. Output process is controlled
by bits in the c_oflag field of the termios structure.
Refer to the write(2) reference manual page for a descrip-
tion of the O_NONBLOCK flag.
The terminal drivers provide for mapping from lowercase to
uppercase (OLCUC) for terminals lacking lower case, and for
other special processing on deficient terminals.
Finally, the terminal driver, supports an output flush char-
acter, normally <Ctrl-O>, which sets the FLUSHO bit in the
local mode word, causing subsequent output to be flushed
until it is cleared by a program or more input is typed.
This character has effect in both canonical and noncanonical
modes and causes any pending input to be retyped. An ioctl
to flush the characters in the input or output queues,
TIOCFLUSH, is also available.
Uppercase Terminals
If the IUCLC bit in the c_iflag field is set in the tty
flags, then all uppercase letters are mapped into the
corresponding lowercase letter. The uppercase letter may be
generated by preceding it by \ (backslash). Uppercase
letters are preceded by a \ (backslash) when output. In
addition, the following escape sequences will be generated
on output and accepted on input if the XCASE bit is set in
the c_lflag word:
For: ` | ~ { }
Use: \' \! \^ \( \)
Line Control and Breaks
There are several ioctl calls available to control the state
of the terminal line. The TIOCSBRK ioctl will set the break
bit in the hardware interface causing a break condition to
exist; this can be cleared (usually after a delay with
sleep(3)) by TIOCCBRK. The tcsendbreak() can also be used
to cause a break condition for a specified amount of time.
Break conditions in the input are handled according to the
c_iflag field settings for the termios structure. Refer to
the section Input Modes" for a complete listing of the
c_iflag field settings. The TIOCCDTR ioctl will clear the
data terminal ready condition; it can be set again by
TIOCSDTR.
When the carrier signal from the dataset drops (usually
because the user has hung up his terminal) a SIGHUP hangup
signal is sent to the processes in the distinguished process
group of the terminal; this usually causes them to ter-
minate. The sending of SIGHUP does not take place if the
CLOCAL bit is set in c_cflag field of the driver. Access to
the terminal by other processes is then normally revoked, so
any further reads will fail, and programs that read a termi-
nal and test for End-of-File on their input will terminate
appropriately.
Interrupt Characters
When the ISIG bit is set in the c_lflag word, there are
several characters that generate signals in both canonical
and noncanonical mode; all are sent to the processes in the
foreground process group of the terminal. If the NOFLSH bit
is not set in c_lflag, these characters also flush pending
input and output when typed at a terminal. The characters
shown here are the defaults; the symbolic names of the
indices of these characters in the c_cc array of the termios
structure are also shown. The characters may be changed.
^C VINTR (in c_cc) generates a SIGINT signal. This
is the normal way to stop a process which is no
longer interesting, or to regain control in an
interactive program.
^\ VQUIT (in c_cc) generates a SIGQUIT signal. This
is used to cause a program to terminate and pro-
duce a core image, if possible, in the file core
in the current directory.
^Z VSUSP (in c_cc) generates a SIGTSTP signal, which
is used to suspend the current process group.
^Y VDSUSP (in c_cc) generates a SIGTSTP signal as
<Ctrl-Z> does, but the signal is sent when a pro-
gram attempts to read the <Ctrl-Y>, rather than
when it is typed.
Terminal Access Control
If a process attempts to read from its controlling terminal
when the process is not in the foreground process group of
the terminal, that background process group is sent a
SIGTTIN signal. This signal normally causes the members of
that process group to stop. If, however, the process is
ignoring SIGTTIN, has SIGTTIN blocked, or if the reading
process' process group is orphaned, the read will return -1
and set errno to [EIO]. The operation will then not send a
signal.
If a process attempts to write to its controlling terminal
when the process is not in the foreground process group of
the terminal, and the TOSTOP bit is set in the c_lflag word
of the termios structure, that background process group is
sent a SIGTTOU signal and the process is prohibited from
writing. If TOSTOP is not set, or if TOSTOP is set and the
process is blocking or ignoring the SIGTTOU signal, process
writes to the terminal are allowed, and the SIGTTOU signal
is not sent. If TOSTOP is set, if the writing process' pro-
cess group is orphaned, and if SIGTTOU is not blocked by the
writing process, the write operation returns a -1 with errno
set to [EIO], and does not a send a signal.
Terminal/Window Sizes
To accommodate terminals and workstations with variable-
sized windows, the terminal driver provides a mechanism for
obtaining and setting the current terminal size. The driver
does not use this information internally, but only stores it
and provides a uniform access mechanism. When the size is
changed, a SIGWINCH signal is sent to the terminal's process
group so that knowledgeable programs may detect size
changes.
tty Parameters
In contrast to earlier versions of the tty driver, the POSIX
terminal parameters and structures are contained in a single
structure, the termios structure defined in the
sys/termios.h file.
Basic ioctl Calls
A large number of ioctl(2) calls apply to terminals. Some
have the general form:
#include <sys/termios.h>
ioctl(fildes, code, arg)
struct termios *arg;
The applicable codes are:
TIOCGETA Gets the termios structure and all its associated
parameters. The interface delays until output is
quiescent, then throws away any unread characters.
TIOCSETA Sets the parameters according to the termios
structure.
TIOCSETAW Drains the output before setting the parameters
according to the termios structure. Sets the
parameters like TIOCSETA.
TIOCSETAF Drains the output and flushes the input before
setting the parameters according to the termios
structure. Sets the parameters like TIOCSETA.
With the following codes arg is ignored:
TIOCEXCL Set "exclusive-use" mode: no further opens are
permitted until the file has been closed.
TIOCNXCL Turn off "exclusive-use" mode.
With the following codes arg is a pointer to an int:
TIOCFLUSH If the int pointed to by arg has a zero value, all
characters waiting in input or output queues are
flushed. Otherwise, the value of the int is for
the FREAD and FWRITE bits defined in the
sys/file.h file; if the FREAD bit is set, all
characters waiting in input queues are flushed,
and if the FWRITE bit is set, all characters wait-
ing in output queues are flushed.
Setting and Unsetting Controlling Terminals
TIOCSCTTY Sets the terminal as the controlling terminal for
the calling process.
TIOCNOTTY Voids the terminal as a controlling terminal.
The following are miscellaneous ioctl terminal
commands. In cases where arguments are required,
they are described; arg should otherwise be given
as 0.
TIOCSTI The argument points to a character which the sys-
tem pretends had been typed on the terminal.
TIOCSBRK The break bit is set in the terminal.
TIOCCBRK The break bit is cleared.
TIOCSDTR Data terminal ready is set.
TIOCCDTR Data terminal ready is cleared.
TIOCSTOP Output is stopped as if the ``stop'' character had
been typed.
TIOCSTART Putput is restarted as if the ``start'' character
had been typed.
TIOCGPGRP The arg parameter is a pointer to an int into
which is placed the process group ID of the pro-
cess group for which this terminal is the control
terminal.
TIOCSPGRP The arg parameter is a pointer to an int which is
the value to which the process group ID for this
terminal will be set.
TIOCOUTQ Returns in the int pointed to by arg the number of
characters queued for output to the terminal.
TIOCREMOTE
Sets the terminal for remote input editing.
FIONREAD returns in the int pointed to by arg the number of
characters immediately readable from the argument
descriptor. This works for files, pipes, and ter-
minals.
Controlling Terminal Modems
The following ioctls apply to modems:
TIOCMODG The arg parameter is a pointer to an int, which is
the value of the modem control state.
TIOCMODS The arg parameter is a pointer to an int, which is
the value to which the modem control state is to
be set.
TIOCMSET Sets all modem bits.
TIOCMBIS The arg parameter is a pointer to an int, which
specifies the modem bits to be set.
TIOCMBIC arg is a pointer to an int, which specifies the
modem bits to be cleared.
TIOCMGET Gets all the modem bits and returns them in the
int point to by arg.
Window/Terminal Sizes
Each terminal has provision for storage of the current ter-
minal or window size in a winsize structure, with format:
struct winsize {
unsigned short ws_row; /* rows, in
characters */
unsigned short ws_col; /* columns, in
characters */
unsigned short ws_xpixel; /* horizontal
size, pixels */
unsigned short ws_ypixel; /* vertical
size, pixels */
};
A value of 0 (zero) in any field is interpreted as ``unde-
fined;'' the entire structure is zeroed on final close.
The applicable ioctl functions are:
TIOCGWINSZ
The arg parameter is a pointer to a struct winsize
into which will be placed the current terminal or
window size information.
TIOCSWINSZ
The arg parameter is a pointer to a struct win-
size, which will be used to set the current termi-
nal or window size information. If the new infor-
mation is different than the old information, a
SIGWINCH signal will be sent to the terminal's
process group.
EXAMPLES
An example of a call to strchg from an application is the
following:
EXAMPLE
An I_PUSH ioctl call from an application to switch line dis-
cipline modules might be coded as follows:
EXAMPLE
FILES
/dev/tty Special file for tty.
/dev/tty* Special files for ttys, where the * (asterisk)
sign represents the tty number.
/dev/console
Device special file for console.
RELATED INFORMATION
Functions: ioctl(2), sigvec(2), tcsetattr(3), tcgetattr(3),
tcdrain(3), tcflush(3), tcsendbreak(3), tcgetpgrp(3),
tcsetpgrp(3)
Commands: csh(1), tset(1), getty(8)
IEEE Std POSIX 1003.1-1988
Application Environment Specification - Operating System
Programming Interfaces Volume
Acknowledgement and Disclaimer