Section 16.5. termios Reference


16.5. termios Reference

The termios interface is composed of a structure, a set of functions that operate on it, and a multitude of flags that you can set individually:

 #include <termios.h> struct termios {     tcflag_t c_iflag;    /* input mode flags */     tcflag_t c_oflag;    /* output mode flags */     tcflag_t c_cflag;    /* control mode flags */     tcflag_t c_lflag;    /* local mode flags */     cc_t c_line;         /* line discipline */     cc_t c_cc[NCCS];     /* control characters */ }; 

The c_line member is used only in very system-specific applications[6] that are beyond the scope of this book. The other five members, however, are relevant in almost all situations that require you to manipulate terminal settings.

[6] Such as setting up networking protocols that communicate through tty devices.

16.5.1. Functions

The termios interface defines several functions, all of which are declared in <termios.h>. Four of them are convenience functions for manipulating a struct termios in a portable way; the rest are system calls. Those that start with cf are convenience functions; those functions that start with tc are terminal control system calls. All of the terminal control system calls generate SIGTTOU if the process is currently running in the background and tries to manipulate its controlling terminal (see Chapter 15).

Except as noted, these functions return 0 to indicate success and -1 to indicate failure. The function calls you may use for terminal control are:

 int tcgetattr(int fd, struct termios *t); 

Retrieves the current settings for the file descriptor fd and places them in the structure to which t points.

 int tcsetattr(int fd, int options, struct termios *t); 

Sets the current terminal settings for the file descriptor fd to the settings specified in t. Always use tcgetattr() to fill in t, then modify it. Never fill in t by hand: Some systems require that flags beyond the flags specified by POSIX be set or cleared, so filling in t by hand is nonportable.

The options argument determines when the change takes effect.


The change takes effect immediately.


The change takes effect after all the output that already has been written to fd has been transmitted; it drains the queue before taking effect. You should generally use this when you change output parameters.


The change takes effect after the output queue has been drained; the input queue is discarded (flushed) before the change takes effect.

If the system cannot handle some settings, such as data rate, it is allowed to ignore those settings silently without returning any error. The only way to see whether the settings were accepted is to use tcgetattr() and compare the contents of the structure it returns to the one you passed to tcsetattr().

Thus, most portable applications use code something like this:

 #include <termios.h> struct termios save; struct termios set; struct termios new; int fd; ... tcgetattr(fd, &save); set = save; cfsetospeed(&set, B2400); cfsetispeed(&set, B2400); tcsetattr(fd, &set); tcgetattr(fd, &new); if ((cfgetospeed(&set) != B2400) ||     (cfgetispeed(&set) != B2400)) {   /* complain */ } 

Note that if you do not care if a termios setting sticks, it is fine to ignore the condition, as we do in robin.

 speed_t cfgetospeed(struct termios *t); speed_t cfgetispeed(struct termios *t); 

Retrieve the output or input speed, respectively, from t. These functions return a symbolic speed, the same as is given to cfsetospeed() and cfsetispeed().

 int cfsetospeed(struct termios *t, speed_t speed); int cfsetispeed(struct termios *t, speed_t speed); 

Set the output or input speed, respectively, in t to speed. Note that this function does not change the speed of the connection on any file descriptor; it merely sets the speed in the termios structure. The speed, like other characteristics, is applied to a file descriptor by tcsetattr().

These functions take a symbolic speed that is, a number that matches the definition of one of the following macros whose names indicate the bits-per-second rate: B0 (0 bits per second indicates a disconnected state), B50, B75, B110, B134,[7] B150, B200, B300, B600, B1200, B1800, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000, B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, or B4000000. B57600 and higher are not specified by POSIX; portable source code uses them only if they are protected by #ifdef statements.

More symbolic speeds will be added to the header file as Linux drivers are written for hardware that supports other data rates.

Currently, input speed is ignored. The termios interface specifies separate input and output speeds for some asynchronous hardware that allows split speeds, but little such hardware exists. Just call cfsetospeed() and cfsetispeed() in pairs so that your code will continue to work on systems that support split speeds.

Not all ttys support all rates. In particular, the serial ports on standard PCs do not support over 115,200 bps. As noted above, if you care whether this setting takes effect, you need to use tcgetattr() to check after you attempt to set it with tcsetattr(). Also, note that the rate you set is advisory. Some ttys, like local consoles, cheerfully accept and ignore any rate you give them.

[7] B134 is really 134.5 bps, a rate used by an obsolete IBM terminal.

 int tcsendbreak(int fd, int duration) 

Sends a stream of zero-valued bits on fd for a specified duration, which is known as a break. If duration is 0, the break is at least 250 milliseconds and no more than 500 milliseconds long. Unfortunately, POSIX did not bother to specify the unit in which the duration is measured, so the only portable value for duration is 0. Under Linux, duration multiplies the break; 0 or 1 specify between a quarter second and a half second; 2 specifies between a half second and a second, and so on.

 int tcdrain(int fd) 

Waits until all currently pending output on the file descriptor fd has been sent.

 int tcflush(int fd, int queue_selector) 

Discards some data on file descriptor fd, depending on the value of queue_selector:


Flush all data that the interface has received but that has not yet been read.


Flush all data that has been written to the interface that has not yet been sent.


Flush all pending data, input and output.

 int tcflow(int fd, int action) 

Suspend or resume output or input on the file descriptor fd. Exactly what to do is determined by action:


Suspend output.


Resume output.


Send a STOP character, requesting that the other end of the connection stop sending characters.


Send a START character, requesting that the other end of the connection resume sending characters.

Note that TCIOFF and TCION are only advisory, and that even if the other end of the connection does honor them, there may be a delay before it does so.

16.5.2. Window Sizes

There are two ioctl() requests that, unfortunately, were not codified as part of the termios interface, although they should have been. The size of the tty, measured in rows and columns, ought to be managed with tcgetwinsize() and tcsetwinsize(), but as they do not exist, you must use ioctl() instead. For both requesting the current size and setting a new size, use a struct winsize:

 #include <termios.h> struct winsize {     unsigned short ws_row;      /* number of rows */     unsigned short ws_col;      /* number of columns */     unsigned short ws_xpixel;   /* unused */     unsigned short ws_ypixel;   /* unused */ }; 

To request the current size, use

 struct winsize ws;  ioctl(fd, TIOCGWINSZ, &ws); 

To set a new size, fill in a struct winsize and call

 ioctl(fd, TIOCSWINSZ, &ws); 

See page 389 for an example of the conditions in which you would want to set a new window size.

When the window size changes, the signal SIGWINCH is sent to the foreground process group leader on that tty. Your code can catch this signal; use TIOCGWINSZ to query the new size and make any appropriate changes within your program.

16.5.3. Flags

The four flag variables, c_iflag, c_oflag, c_cflag, and c_lflag, hold flags that control various characteristics. The <termios.h> header file provides symbolic constant bitmasks that represent those flags. Set them with |= and unset them with &= ~, like this:

 t.c_iflag |= BRKINT; t.c_iflag &= ~IGNBRK; 

A few of these symbolic defines are actually bitmasks that cover several related constants. They are used to extract parts of the structure for comparison:

 if ((t.c_cflag & CSIZE) == CS7)   character_size = 7; 

The set of flags differs from system to system. The most important flags are specified by POSIX, but Linux follows System V in including several useful flags that POSIX does not define. This documentation is not complete; Linux supports some flags that you will probably never need. We cover the flags that you might possibly have a reason to use and refrain from confusing you with the rest.

In order to enable you to write portable software, we have labelled every flag that is not specified by the POSIX standard. For those flags, you should write code like this:

 #ifdef IUCLC     t.c_iflag |= IUCLC; #endif 

Also, some areas that present particular portability problems are mentioned, and we even break our rule of not confusing you with details from other implementations by presenting a few details about what other systems do.

16.5.4. Input Flags

The input mode flags affect input processing even though they sometimes have an effect on output. The flags that operate on c_iflag are as follows:


If IGNBRK is set, break conditions (see tcsendbreak(), mentioned earlier) are ignored.


If IGNBRK is not set and BRKINT is set, break conditions cause the tty to flush all queued input and output data and send a SIGINT to processes in the foreground process group for the tty.


If IGNBRK is not set and BRKINT is not set, break conditions are read as a zero-valued character ('\0'), except if PARMRK is set, in which case a framing error is detected and the three bytes '\377' '\0' '\0' are delivered to the application instead.


If IGNPAR is set, received bytes containing parity or framing errors are ignored (except as specified for break conditions earlier).


If IGNPAR is not set and PARMRK is set, a received byte with a parity or framing error is reported to the application as the three-byte sequence '\377' '\0' '\n', where n is the byte as it was received. In this case, if ISTRIP is not set, a valid '\377' character is reported to the application as the two-character sequence '\377' '\377'; if ISTRIP is set, a '\377' character has its high bit stripped and is reported as '\177'.


If neither PARMRK nor IGNPAR is set, a received byte with a parity or framing error other than a break condition is reported to the application as a single '\0' character.


If INPCK is set, parity checking is enabled. If it is not enabled, PARMRK and IGNPAR have no effect on received parity errors.


If ISTRIP is set, the high-order bit is stripped from all received bytes, limiting them to seven bits.


If INLCR is set, received newline ('\n')characters are translated to carriage-return ('\r') characters.


If IGNCR is set, received carriage returns ('\r') are ignored (not reported to the application).


If ICRNL is set and IGNCR is not set, received carriage-return ('\r') characters are reported to the application as newline ('\n') characters.


If IUCLC and IEXTEN are set, received uppercase characters are reported to the application as lowercase characters. This flag is not specified by POSIX.


If IXOFF is set, the tty may send Control-S and Control-Q characters to the terminal to request that it stop and resume output (that is, sending data to the computer), respectively, to avoid overflowing the tty's input buffers. This is relevant only to serial terminals, as network and local terminals have more direct forms of flow control. Even serial terminals often have hardware flow control, which is controlled by the control flag (c_cflag) and which makes software flow control (Control-S and Control-Q) irrelevant.


If IXON is set, a received Control-S character stops output to this tty and a received Control-Q character restarts output to this tty. This is relevant to any form of terminal I/O, as some users type literal Control-S and Control-Q characters to suspend and resume output.


If IXANY is set, any received character (not just Control-Q) restarts output. This flag is not specified by POSIX.


If IMAXBEL is set, the alert ('\a') character is sent whenever a character is received and the input buffer is already full. This flag is not specified by POSIX.

16.5.5. Output Flags

The output mode flags modify output processing only if OPOST is set. None of these flags are portable, because POSIX defines only OPOST and calls it "implementation defined." However, you will find that real terminal-handling applications often do need output processing, and the output flags available under Linux are generally available on most Unix systems, including SVR4.

The terminal code keeps track of the current column, which allows it to suppress extra carriage-return characters ('\r') and to convert tabs to spaces when appropriate. This current column is zero-based; the first column is column zero. The current column is set to zero whenever a carriage return ('\r')is sent or implied, as it may be by a newline character ('\n') when ONLRET or ONLCR is set, or when the current column is set to one and a backspace character ('\b') is sent.

The flags that operate on c_oflag are as follows:


This is the only output flag specified by POSIX, which says that it turns on "implementation-defined" output processing. If OPOST is not set, none of the other output mode flags are consulted and no output processing is done.


If OLCUC is set, lowercase characters are sent to the terminal as uppercase characters. This flag is not specified by POSIX.


If ONLCR is set, when a newline character ('\n') is sent, a carriage return ('\r') is sent before the newline. The current column is set to zero. This flag is not specified by POSIX.


If ONOCR is set, carriage-return characters ('\r') are neither processed nor sent if the current column is zero. This flag is not specified by POSIX.


If OCRNL is set, carriage-return characters ('\r') are translated into newline characters ('\n'). If, in addition, ONLRET is set, the current column is set to zero. This flag is not specified by POSIX.


If ONLRET is set, when a newline character ('\n') or carriage-return character ('\r')is sent, the current column is set to zero. This flag is not specified by POSIX.


If OXTABS is set, tabs are expanded to spaces. Tab stops are assumed to be every eight characters, and the number of space characters that are sent is determined by the current column. This flag is not specified by POSIX.

In addition, there are delay flags that you never need to set; they are designed to compensate for old, badly designed, and, by now, mercifully rare hardware. The termcap and terminfo libraries are responsible for managing delay flags, which means that you should never have to modify them. termcap & terminfo [Strang, 1991B], which documents them, describes them as obsolete. The Linux kernel does not currently implement them, and as there has been no demand for this feature, they likely will never be implemented.

16.5.6. Control Flags

The control mode flags affect protocol parameters, such as parity and flow control.[8] The flags that operate on c_cflag are as follows:

[8] Linux also uses c_cflag to hold the speed, but relying on that is completely nonportable. Use cfsetospeed() and cfsetispeed() instead.


If CLOCAL is set, modem control lines are ignored. If it is not set, then open() will block until the modem announces an off-hook condition by asserting the carrier-detect line.


Characters can be received only if CREAD is set. It cannot necessarily be unset.[9]


CSIZE is a mask for the codes that set the size of a transmitted character in bits. The character size should be set to:
CS5 for five bits per character
CS6 for six bits per character
CS7 for seven bits per character
CS8 for eight bits per character


If CSTOPB is set, two stop bits are generated at the end of each transmitted character frame. If CSTOPB is not set, only one stop bit is generated. Obsolete equipment that requires two stop bits is rare.


If HUPCL is set, then when the final open file descriptor on the device is closed, the DTR and RTS lines on the serial port (if they exist) will be lowered to signal the modem to hang up. This means, for example, that when a user who logged in through a modem then logs out, the modem will be hung up. If a communications program has the device open for outbound calls and the process then closes the device (or exits), the modem will be hung up.


If PARENB is set, a parity bit is generated. If PARODD is not set, even parity is generated. If PARODD is set, odd parity is generated.


If PARENB is not set, PARODD is ignored.


Use hardware flow control (RTS and CTS lines). At high speeds (19,200 bps and higher) software flow control via the XON and XOFF characters becomes ineffective and hardware flow control must be used instead.


This flag is not specified by POSIX and is not available by this name on most other Unix systems. This is a particularly nonportable area of terminal control, despite the common need for hardware flow control on modern systems. SVR4 is particularly egregious in that it provides no way to enable hardware flow control through termios, only through a different interface called termiox.

[9] Try running stty -cread!

16.5.7. Control Characters

Control characters are characters that have special meanings that may differ depending on whether the terminal is in canonical input mode or raw input mode and on the settings of various control flags. Each offset (except for VMIN and VTIME) in the c_cc array designates an action and holds the character code that is assigned that action. For example, set the interrupt character to Control-C with code like this:

 ts.c_cc[VINTR] = CTRLCHAR('C'); 

CTRLCHAR() is a macro defined as

 #define CTRLCHAR(ch) ((ch)&0x1F) 

Some systems have a CTRL() macro defined in <termios.h>, but it is not defined on all systems, so defining our own version is more portable.

We use the ^C notation to designate Control-C.

The character positions that are not specified by POSIX are active only if the IEXTEN local control (c_lflag) flag is set.

The control characters that you can use as subscripts to the c_cc array are:


Offset VINTR is usually set to ^C. It normally flushes the input and output queues and sends SIGINT to the members of the foreground process group associated with the tty. Processes that do not explicitly handle SIGINT will exit immediately.


Offset VQUIT is usually set to ^\. It normally flushes the input and output queues and sends SIGQUIT to the members of the foreground process group associated with the tty. Processes that do not explicitly handle SIGQUIT will abort, dumping core if possible (see page 120).


Offset VERASE is usually set to ^H or ^?. In canonical mode, it normally erases the previous character on the line. In raw mode, it is meaningless.


Offset VKILL is usually set to ^U. In canonical mode, it normally erases the entire line. In raw mode, it is meaningless.


Offset VEOF is usually set to ^D. In canonical mode, it causes read() on that file descriptor to return 0, signaling an end-of-file condition. On some systems, it may share space with the VMIN character, which is active only in raw mode. (This is not an issue if you save a struct termios with canonical mode settings to restore once you are done with raw mode, which is proper termios programming practice, anyway.)


Offset VSTOP is usually set to ^S. It causes the tty to pause output until the VSTART character is received, or, if IXANY is set, until any character is received.


Offset VSTART is usually set to ^Q. It restarts paused tty output.


Offset VSUSP is usually set to ^Z. It causes the current foreground process group to be sent SIGTSTP; see Chapter 15 for details.


In canonical mode, these characters, in addition to the newline character ('\n'), signal an end-of-line condition. This causes the collected buffer to be transmitted and a new buffer started. On some systems, VEOL may share space with the VTIME character, which is active only in raw mode, just as VEOF may share space with VMIN. The VEOL2 character is not specified by POSIX.


Offset VREPRINT is usually set to ^R. In canonical mode, if the ECHO local flag is set, it causes the VREPRINT character to be echoed locally, a newline (and a carriage return, if appropriate) to be echoed locally, and the whole current buffer to be reprinted. This character is not specified by POSIX.


Offset VWERASE is usually set to ^W. In canonical mode, it erases any white space at the end of the buffer, then all adjacent non-white-space characters, which has the effect of erasing the previous word on the line. This character is not specified by POSIX.


Offset VLNEXT is usually set to ^V. It is not itself entered into the buffer, but it causes the next character input to be put into the buffer literally, even if it is one of the control characters. Of course, to enter a single literal VLNEXT character, type it twice. This character is not specified by POSIX.

To disable any control character position, set its value to _POSIX_VDISABLE. This only works if _POSIX_VDISABLE is defined, and is defined as something other than -1. _POSIX_VDISABLE works on Linux, but a portable program will, unfortunately, not be able to depend on disabling control character positions on all systems.

16.5.8. Local Flags

The local mode flags affect local processing, which (roughly) refers to how characters are collected before they are output. When the device is in canonical (cooked) mode, characters are echoed locally without being sent to the remote system until a newline character is encountered. At that point, the whole line is sent, and the remote end processes it without echoing it again. In raw mode, each character is sent to the remote system as it is received. Sometimes the character is echoed only by the remote system; sometimes only by the local system; and sometimes, such as when reading a password, it is not echoed at all.

Some flags may act differently, depending on whether the terminal is in canonical mode or raw mode. Those that act differently in canonical and raw mode are marked.

The flags that operate on c_lflag are as follows:


If ICANON is set, canonical mode is enabled. If ICANON is not set, raw mode is enabled.


If ECHO is set, local echo is enabled. If ECHO is not set, all the other flags whose names start with ECHO are effectively disabled and function as if they are not set, except for ECHONL.


If ECHOCTL is set, control characters are printed as ^C, where C is the character formed by adding octal 0100 to the control character, mod octal 0200. So Control-C is displayed as ^C, and Control-? (octal 0177) is represented as ^? (? is octal 77). This flag is not specified by POSIX.


In canonical mode, if ECHOE is set, then when the ERASE character is received, the previous character on the display is erased if possible.


In canonical mode, when the KILL character is received, the entire current line is erased from the buffer.


If neither ECHOK, ECHOKE, nor ECHOE is set, the ECHOCTL representation of the KILL character (^U by default) is printed to indicate that the line has been erased.


If ECHOE and ECHOK are set but ECHOKE is not set, the ECHOCTL representation of the KILL character is printed, followed by a newline, which is then processed appropriately by OPOST handling if OPOST is set.


If ECHOE, ECHOK, and ECHOKE are all set, the line is erased.


See the description of ECHOPRT for another variation on this theme.


The ECHOKE flag is not specified by POSIX. On systems without the ECHOKE flag, setting the ECHOK flag may be equivalent to setting both the ECHOK and ECHOKE flags under Linux.


In canonical mode, if ECHONL is set, newline ('\n') characters are echoed even if ECHO is not set.


In canonical mode, if ECHOPRT is set, characters are printed as they are erased when the ERASE or WERASE (or KILL, if ECHOK and ECHOKE are set) characters are received. When the first erase character in a sequence is received, a \ is printed, and when the final erased character is printed (the end of the line is reached or a nonerasing character is typed), a / is printed. Every normal character you type is merely echoed. So typing asdf, followed by two ERASE characters, followed by df, followed by a KILL character, would look like asdf\fd/df\fdsa/


This is useful for debugging and for using hardcopy terminals, such as the original teletype, where the characters are printed on paper, and is otherwise useless. This flag is not specified by POSIX.


If ISIG is set, the INTR, QUIT, and SUSP control characters cause the corresponding signal (SIGINT, SIGQUIT, or SIGTSTP, respectively; see Chapter 12) to be sent to all the processes in the current foreground process group on that tty.


Usually, when the INTR and QUIT characters are received, the input and output queues are flushed. When the SUSP character is received, only the input queue is flushed. If NOFLSH is set, neither queue is flushed.


If TOSTOP is set, then when a process that is not in the current foreground process group attempts to write to its controlling terminal, SIGTTOU is sent to the entire process group of which the process is a member. By default, this signal stops a process, as if the SUSP character had been pressed.


This flag is specified as implementation-dependent by POSIX. It enables implementation-defined processing of input characters. Although portable programs do not set this bit, the IUCLC and certain character-erasing facilities in Linux depend on it being set. Fortunately, it is generally enabled by default on Linux systems, because the kernel initially enables it when setting up ttys, so you should not normally need to set it for any reason.

16.5.9. Controlling read()

Two elements in the c_cc array are not control characters and are relevant only in raw mode: VTIME and VMIN. In raw mode only, these determine when read() returns. In canonical mode, read() returns only when lines have been assembled or end-of-file is reached, unless the O_NONBLOCK option is set.

In raw mode, it would not be efficient to read one byte at a time, and it is also inefficient to poll the port by reading in nonblocking mode. This leaves two complementary methods of reading efficiently.

The first is to use poll(), as documented in Chapter 13 and demonstrated in robin.c. If poll() says that a file descriptor is ready to read, you know that you can read() some number of bytes immediately. However, combining poll() with the second method can make your code even more efficient by making it possible to read more bytes at a time.

The VTIME and VMIN "control characters" have a complex relationship. VTIME specifies an amount of time to wait in tenths of seconds (which cannot be larger than a cc_t, usually an 8-bit unsigned char), which may be zero. VMIN specifies the minimum number of bytes to wait for (not to read read()'s third argument specifies the maximum number of bytes to read), which may also be zero.

  • If VTIME is zero, VMIN specifies the number of bytes to wait for. A read() call does not return until at least VMIN bytes have been read or a signal has been received.

  • If VMIN is zero, VTIME specifies the number of tenths of seconds for read() to wait before returning, even if no data is available. In this case, read() returning zero does not necessarily indicate an end-of-file condition, as it usually does.

  • If neither VTIME nor VMIN is zero, VTIME specifies the number of tenths of seconds for read() to wait after at least one byte is available. If data is available when read() is called, a timer starts immediately. If data is not available when read() is called, a timer is started when the first byte arrives. The read() call returns either when at least VMIN bytes have arrived or when the timer expires, whichever comes first. It always returns at least one byte because the timer does not start until at least one byte is available.

  • If VTIME and VMIN are both zero, read() always returns immediately, even if no data is available. Again, zero does not necessarily indicate an end-of-file condition.


    Linux Application Development
    Linux Application Development (paperback) (2nd Edition)
    ISBN: 0321563220
    EAN: 2147483647
    Year: 2003
    Pages: 168

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: