Termios functions-tcgetattr, tcsetattr, tcsendbreak, tcdrain, tcflush, tcflow, cfmakeraw, cfgetospeed, cfgetispeed, cfsetispeed, cfsetospeed, cfsetspeed, etc, used to obtain/set the properties, control, and speed of a terminal device.
1. function declaration
Function Declaration
# Include <termios. h> # include <unistd. h>/* put the device status corresponding to the file descriptor FD to the struct pointed to by termios_p */INT tcgetattr (int fd, struct termios * termios_p ); /* set the device status corresponding to the file descriptor */INT tcsetattr (int fd, int optional_actions, const struct termios * termios_p ); /* Send 0 bits to fd */INT tcsendbreak (int fd, int duration);/* suspend until all output data written to FD is sent completely */INT tcdrain (int fd ); /* discard all data that is to be written but not sent to fd or data that has been received but not read from Fd * // * the discarded object depends on queue_selector */INT tcflush (int fd, int queue_selector);/* Pending FD sending or receiving operations. The pending object depends on action */INT tcflow (int fd, int action ); /* Device terminal attributes */void cfmakeraw (struct termios * termios_p);/* returns the input baud rate */speed_t cfgetispeed (const struct termios * termios_p ); /* return the output baud rate */speed_t cfgetospeed (const struct termios * termios_p) pointed to by termios_p ); /* set the input baud rate */INT cfsetispeed (struct termios * termios_p, speed_t speed) pointed to by termios_p ); /* set the output baud rate */INT cfsetospeed (struct termios * termios_p, speed_t speed) in the struct directed by termios_p;/* 4.4bsd extension, set the input/output baud rate */INT cfsetspeed (struct termios * termios_p, speed_t speed );
Glibc function test macro definition:
cfsetspeed(), cfmakeraw(): _BSD_SOURCE
2. termios struct
Most termios functions use the termios structure. The termios struct is defined as follows:
typedef unsigned char cc_t;typedef unsigned int speed_t;typedef unsigned int tcflag_t;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 */speed_t c_ispeed; /* input speed */speed_t c_ospeed; /* output speed */#define _HAVE_STRUCT_TERMIOS_C_ISPEED 1#define _HAVE_STRUCT_TERMIOS_C_OSPEED 1};
C_iflag flag constant
Ignbrk ignores input break Conditions
If ignbrk is set for brkint, break will be ignored. If only brkint is set, break will discard the data in the input and output queues (flush ), if the terminal is the control terminal of the foreground process group, break will generate a SIGINT signal and send it to the foreground process group. If ignbrk and brkint are not set, break will be read as a NULL byte ('\ 0'), unless the parmrk flag is set, in this case, break is read as the \ 377 \ 0 \ 0 sequence.
Ignpar ignores frame errors and parity errors
If the ignpar flag is not set for parmrk, \ 377 \ 0 is used before characters with a parity error or frame error. If neither ignpar nor parmrk is set, the characters with incorrect parity are treated as \ 0.
Inpck allows input parity
Istrip stripped 8th bits
Inlcr converts the input NL to Cr
Igncr ignore the carriage return in the input
Icrnl converts the Cr in the input to Nl
Iuclc (non-POSIX) converts uppercase characters in the input to lowercase letters
Ixon allows Xon/xoff throttling at the output end
Any ixany (xsi) Key will restart the stopped output (by default, only start characters are allowed to restart the output)
Ixoff allows incoming Xon/xoff throttling
When the imaxbel (non-POSIX) input queue is full, the bell rings. This flag is not implemented in Linux, and is always set in this flag.
Iutf8 (supported from Linux 2.6.4, non-POSIX) input is UTF-8 encoded
C_oflag flag constant definition (posix.1 ):
Opost allows output processing defined
Olcuc (non-POSIX) maps lowercase letters in the output to uppercase letters
Onlcr (xsi) maps the NL in the output to the CR-NL
Ocrnl maps the Cr in the output to Nl
Onocr does not output Cr in column 0
Onlret does not output cr
Ofill sends padding characters to achieve latency, instead of time latency.
Ofdel (non-POSIX) is filled with ASCII del (0177 ). If not set, the filling character is ascii nul ('\ 0 '). (Not implemented in Linux)
Nldly new line delay mask. The values are nl0 and nl1. (_ Bsd_source, _ svid_source, or _ xopen_source is required)
Crdly press enter (CR) Delay mask. The value is Cr0, CR1, CR2, or C3. (_ Bsd_source, _ svid_source, or _ xopen_source is required)
Tabdly horizontal tab latency mask. The value is tab0, tab1, tab2, tab3 (or xtabs ). The value tab3/xtabs indicates that the tab is expanded to spaces (each 8 columns are listed as a tab stop bit ). (_ Bsd_source, _ svid_source, or _ xopen_source is required)
Latency mask of bsdly rollbacks. Value: bs0 or bs1. (never implemented) (required: _ bsd_source, _ svid_source, or _ xopen_source)
Vtdly vertical tab latency mask. The value is vt0 or vt1.
Ffdly form input latency mask. The value is ff0 or ff1. (_ bsd_source or _ svid_source or _ xopen_source is required)
C_cflag flag constant:
Cbaud (non-POSIX) Port rate mask (4 + 1 bit ). (_ Bsd_source, _ svid_source, or _ xopen_source is required)
Cbaudex (non-POSIX) attaches the port rate mask (1 bit), which is included in cbaud. (_ Bsd_source, _ svid_source, or _ xopen_source is required)
Csize character size mask. The value is cs5, CS6, cs7, or cs8.
Cstopb sets two bits instead of one
Cread allows the receiver
Parenb allows the output end to produce parity bits for input end verification.
If parodd is set, the parity check at the input output end is odd. If not set, the parity check is performed.
After the last operation of hupcl shut down the device, set the modem control line to low (suspended)
Clocal ignores modem control lines
Loblk (non-POSIX) blocks non-current shell layer output. (Not implemented in Linux)
Cibaud (non-POSIX) Input Rate mask.
Cmspar (non-POSIX) uses "stick" parity: If parodd is set, the parity bit is always set to 1. If parodd is not set, the parity bit is always set to 0.
Crtscts allows the flow control of RTS/CTS (hardware. (_ Bsd_source or _ svid_source is required)
C_lflag flag constant:
When isig receives the intr/quit/susp/dsusp character, a corresponding signal is generated.
Icanon allows canonical Mode
Xcase (not POSIX, not supported in Linux) If icanon is set, the terminal only uses the uppercase character mode. The input character is converted to lowercase letters, except starting with '\'; Output end, capital letters starting with '\', and lowercase characters converted to uppercase letters
Echo character
If the icanon flag is set for echoe, erase deletes the previous character and werase deletes the previous word.
If the icanon flag is set at the same time, the kill character deletes the current row.
If the icanon flag is set at the same time, echo the NL character even if ECHO is not set
Echoctl (non-POSIX) if the echo flag is set at the same time, ASCII control characters except TAB/NL/start/stop will be displayed as '^ x ', X is the control character value plus 0x40.
Echoprt (non-POSIX) if both icanon and iecho are set, the characters are printed as deleted
Echoke (non-POSIX) If icanon is set, kill to delete all characters in the row
Defecho (non-POSIX) only echo characters when a process reads data (not implemented in Linux)
Flusho (not POSIX, not supported by Linux) output is discarded.
Noflsh: Do not discard (flush) input/output queue when generating SIGINT, sigquit, and sigsusp Signals
Tostop: When the background process tries to write data to its own control terminal, it sends the sigttou signal to the process group.
Pendin (non-POSIX, not supported by Linux)
Iexten allows defined input processing.
The c_cc array defines some special control characters:
Vintr 003, etx, Ctrl-C, 0177, Del, rubout, and interrupt characters. Send a SIGINT signal.
Vquit 034, FS, Ctrl-\, exit character. Send a sigquit signal.
Verase 0177, Del, rubout, 010, BS, Ctrl-h, #, delete characters. Delete the last undeleted character, but do not delete the previous EOF or line start character.
Vkill 025, Nak, Ctrl-u, cgtrl-X, @, and kill characters. Delete all input characters after the previous EOF or line start character.
Veof 004, EOT, Ctrl-D, end-of-file ). The EOF sends the suspended tty buffer content to the user program in the waiting state, instead of waiting for the end-of-line (end-of-line ).
Minimum number of characters for Vmin read operations in non-canonical Mode
Veol (0, NUL) Additional line terminator (end-of-line)
Vtime non-canonical mode read operation timeout (unit: 1/10 seconds)
Veol2 (non-POSIX; 0, NUL) end ID of another row
Vswtch (non-POSIX; not supported in Linux; 0, NUL) switch characters
Vstart 021, DC1, Ctrl-Q, and start character. Restart output with stopped characters
Vstop 023, DC3, Ctrl-S, stop character. Stop output until start
Vsusp 032, sub, Ctrl-Z, and suspension character. Send sigstp Signal
Vdsusp (not POSIX; not supported by Linux) 031, em, Ctrl-y, delayed suspension character: Send sigtstp signal when the user program reads the character
Vlnext (non-POSIX) 026, Syn, Ctrl-V, identifies the next character as a literal rather than a possible special control meaning
Vwerase (non-POSIX) 027, etc, Ctrl-W, word Deletion
Vreprint (non-POSIX) 022, DC2, Ctrl-R, print unread characters again
Vdiscard (not POSIX; not supported by Linux) 017, Si, Ctrl-o, switch: start/stop discard pending output
Vstatus (not POSIX; not supported in Linux) 024, dc4, Ctrl-T, Status Request
3. Get/change terminal settings
Tcgetattr () and tcsetattr () are used to obtain/change terminal settings respectively.
Tcgetattr () obtains the settings of the terminal specified by FD and puts them in the address space pointed to by the termios structure pointer termios_p. The terminal settings obtained by the background process may also be changed by the foreground process.
Tcsetattr () sets the properties of the specified terminal. Optional action items specify when terminal properties will be changed:
Tcsanow change now
Tcsadrain changes when all output data written to FD is sent
Tcsaflush: After all output data written to FD is sent, and all received but not read inputs are discarded, change the settings.
4. canonical and non-canonical Modes
The icanon flag in the c_lflag field determines whether the terminal works in the canonical mode. By default, the terminal is in Canonical mode.
Canonical Mode
Enter the working row mode. After receiving the line delimiters (NL, EOL, eol2; or EOF at the beginning of the line), the input line can be read. The row content read by the read operation contains the line delimiters.
Allow row editing (erase, kill; for example, set iexten flag, werase, reprint, lnext ).
In non-canonical mode, the input can be read immediately without entering the line delimiter.
Impact of c_cc [vtime] And c_cc [Vmin] On read operations:
Min = 0; time = 0: if data is available, read immediately returns min (number of requests, number of available characters); if no data is available, read returns 0
Min> 0; time = 0: Read blocking until at least min (number of requests, min) characters are available. Read returns a smaller value
Min = 0; time> 0: Time specifies the read timeout (unit: 1/10 seconds ). Set the timer when you call read. When at least one character is available or times out, read returns. If no character is available before the timeout, read returns 0
Min> 0; time> 0: time indicates read timeout. After receiving the first character, restart the timer. Read reads a small number of characters from min and the number of requests, or returns the result after timeout. At least one character is read.
5. Raw Mode
Cfmakeraw () sets the terminal to work in "Raw" Mode: the input is provided in character mode, prohibit echo, and all special characters are forbidden.
In RAW mode, the terminal attributes are as follows:
termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
| INLCR | IGNCR | ICRNL | IXON);
termios_p->c_oflag &= ~OPOST;
termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
termios_p->c_cflag &= ~(CSIZE | PARENB);
termios_p->c_cflag |= CS8;
termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);termios_p->c_oflag &= ~OPOST;termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);termios_p->c_cflag &= ~(CSIZE | PARENB);termios_p->c_cflag |= CS8;
6. Line Control
Control and terminal connection
If the terminal works in the asynchronous serial data transmission mode, the tcsendbreak sends a 0-bit stream within the specified duration. If the length is 0, 0 bits are sent for at least 0.25 s, but not more than 0.5 s. If the terminal does not work in asynchronous serial data transmission mode, tcsendbreak returns immediately without any operation.
Tcdrain () waits until all data output to FD is sent
Tcflush () discards data that has been written to fd but has not yet been sent, or discarded data that has been received but not read. The discarded object depends on queue_selector:
Tciflush discards received but not read data
Tcoflush discards data that has been written but has not been sent
Tcioflush discard the above two types
Tcflow () suspends the sending or receiving operation of FD. Pending objects depends on action:
Tcooff pending output
Output of pending tcoon restart
Tcioff sends stop characters to stop devices from sending data to the System
Tcion sends the start character, and the startup device sends data to the System
7. wire speed
Control Input/Output baud rate
Setting the baud rate to B0 will suspend the modem (Hang UP ). The actual rate of b38400 may be affected by setserial (8.
Cfgetospeed () returns the output baud rate
Cfsetospeed () set the output baud rate to B0/B50/b75/b110/b134/b150/b200/b300/b600/b1200/b1800/b2400/b4800/b9600/b38400/b57600/b115200/b230400 * b0 is used to terminate the connection
Cfgetispeed () returns the input baud rate
Cfsetispeed () sets the input baud rate
Cfsetspeed () 4.4bsd extension, and set the input baud rate to the same value
8. Return Value
Identify the function call result
Cfgetispeed ()/cfgetospeed () returns the input/output baud rate
For other functions, if the returned value is 0, it indicates success;-1 indicates failure, and errno indicates an error * For tcsetattr (), if any attribute to be modified is set successfully, success is returned.
9. Example
Obtain the attributes of the Standard Input Terminal (stdin) and change the standard input terminal to the RAW mode (you can also use the more convenient call-cfmakeraw () to receive keyboard input and display key values, until the Ctrl-B input is received.
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#define BUF_LENGTH 255
int main(void)
{
int ret = 0;
char buf[BUF_LENGTH]={0};
int i = 0;
struct termios newtmios={0};
struct termios oldtmios={0};
ret = tcgetattr(STDIN_FILENO, &oldtmios);
if ( ret )
{
printf("tcgetattr() error, errno = 0x%X\n", errno);
return -1;
}
memcpy(&newtmios, &oldtmios, sizeof(struct termios));
newtmios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
| INLCR | IGNCR | ICRNL | IXON);
newtmios.c_oflag &= ~OPOST;
newtmios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
newtmios.c_cflag &= ~(CSIZE | PARENB);
newtmios.c_cflag |= CS8;
ret = tcsetattr(STDIN_FILENO, TCSANOW, &newtmios);
if ( ret )
{
printf("tcsetattr() error, errno = 0x%X\n", errno);
return -2;
}
printf("Press any key(Ctrl-b to quit) :\n ");
tcdrain(STDIN_FILENO);
while ( 1 )
{
ret = read(STDIN_FILENO, buf, BUF_LENGTH);
if ( ret )
{
printf("\rread %d chars, you pressed ", ret);
for(i=0; i<ret;i++) printf(" 0x%02X ", buf[i]);
printf("\r\n");
if ( (1==ret) && (0x02 == buf[0]) )
{
break;
}
}
}
ret = tcsetattr(STDIN_FILENO, TCSANOW, &oldtmios);
return ret;
}