串口程序设计——struct termios结构体

一、数据成员
termios 函数族提供了一个常规的终端接口,用于控制非同步通信端口。 这个结构包含了至少下列成员: 
tcflag_t c_iflag;      /* 输入模式 */
tcflag_t c_oflag;      /* 输出模式 */
tcflag_t c_cflag;      /* 控制模式 */
tcflag_t c_lflag;      /* 本地模式 */
cc_t c_cc[NCCS];       /* 控制字符 */
struct termios
{unsigned short c_iflag; /* 输入模式标志*/
unsigned short c_oflag; /* 输出模式标志*/
unsigned short c_cflag; /* 控制模式标志*/
unsigned short c_lflag; /*区域模式标志或本地模式标志或局部模式*/
unsigned char c_line; /*行控制line discipline */
unsigned char c_cc[NCC]; /* 控制字符特性*/
};
二、作用

这个变量被用来提供一个健全的线路设置集合, 如果这个端口在被用户初始化前使用. 驱动初始化这个变量使用一个标准的数值集, 它拷贝自 tty_std_termios 变量. tty_std_termos 在 tty 核心被定义为:

struct termios tty_std_termios = {  .c_iflag = ICRNL | IXON,  .c_oflag = OPOST | ONLCR,  .c_cflag = B38400 | CS8 | CREAD | HUPCL,  .c_lflag = ISIG | ICANON | ECHO | ECHOE | ECHOK |  ECHOCTL | ECHOKE | IEXTEN,  .c_cc = INIT_C_CC };
这个 struct termios 结构用来持有所有的当前线路设置, 给这个 tty 设备的一个特定端口. 这些线路设置控制当前波特率, 数据大小, 数据流控设置, 以及许多其他值. 
三、成员的值
(一)c_iflag 标志常量:
Input mode ( 输入模式)

    
    
    
    
input mode可以在输入值传给程序之前控制其处理的方式。

       
       
       
       
其中输入值可能是由序列埠或键盘的终端驱动程序所接收到的字元。
我们可以利用termios结构的c_iflag的标志来加以控制,其定义的方式皆以OR来加以组合。
    • IGNBRK :忽略输入中的 BREAK 状态。 忽略命令行中的中断
    • BRKINT :命令行出现中断时,可产生一插断)如果设置了 IGNBRK,将忽略 BREAK。如果没有设置,但是设置了 BRKINT,那么 BREAK 将使得输入和输出队列被刷新,如果终端是一个前台进程组的控制终端,这个进程组中所有进程将收到 SIGINT 信号。如果既未设置 IGNBRK 也未设置 BRKINT,BREAK 将视为与 NUL 字符同义,除非设置了 PARMRK,这种情况下它被视为序列 377 � �。 
    • IGNPAR :忽略桢错误和奇偶校验错。 
    • PARMRK :如果没有设置 IGNPAR,在有奇偶校验错或桢错误的字符前插入 377 �。如果既没有设置 IGNPAR 也没有设置 PARMRK,将有奇偶校验错或桢错误的字符视为 �。 
    • INPCK :启用输入奇偶检测。 
    • ISTRIP :去掉第八位。 
    • INLCR :将输入中的 NL 翻译为 CR。将收到的换行符号转换为Return 
    • IGNCR :忽略输入中的回车。 
    • ICRNL :将输入中的回车翻译为新行 (除非设置了 IGNCR)(否则当输入信号有 CR 时不会终止输入)。 
    • IUCLC :(不属于 POSIX) 将输入中的大写字母映射为小写字母。 
    • IXON :启用输出的 XON/XOFF 流控制。  
    • IXANY :(不属于 POSIX.1;XSI) 允许任何字符来重新开始输出。(?) 
    • IXOFF :启用输入的 XON/XOFF 流控制。 
    • IMAXBEL:(不属于 POSIX) 当输入队列满时响零。Linux 没有实现这一位,总是将它视为已设置。 
(二) c_oflag 标志常量: Output mode ( 输出模式)
Output mode主要负责控制输出字元的处理方式。输出字元在传送到序列埠或显示器之前是如何被程序来处理。
输出模式是利用termios结构的c_oflag的标志来加以控制,其定义的方式皆以OR来加以组合。 
    • OPOST :启用具体实现自行定义的输出处理。 
    • OLCUC :(不属于 POSIX) 将输出中的小写字母映射为大写字母。 
    • ONLCR :(XSI) 将输出中的新行符映射为回车-换行。 
    • OCRNL :将输出中的回车映射为新行符 
    • ONOCR :不在第 0 列输出回车。 
    • ONLRET :不输出回车。 
    • OFILL :发送填充字符作为延时,而不是使用定时来延时。 
    • OFDEL :(不属于 POSIX) 填充字符是 ASCII DEL (0177)。如果不设置,填充字符则是 ASCII NUL。 
    • NLDLY :新行延时掩码。取值为 NL0 和 NL1。 
    • CRDLY :回车延时掩码。取值为 CR0, CR1, CR2, 或 CR3。 
    • TABDLY :水平跳格延时掩码。取值为 TAB0, TAB1, TAB2, TAB3 (或 XTABS)。取值为 TAB3,即 XTABS,将扩展跳格为空格 (每个跳格符填充 8 个空格)。(?) 
    • BSDLY :回退延时掩码。取值为 BS0 或 BS1。(从来没有被实现过) 
    • VTDLY :竖直跳格延时掩码。取值为 VT0 或 VT1。 
    • FFDLY :进表延时掩码。取值为 FF0 或 FF1。
(三) c_cflag 标志常量: Control mode ( 控制模式)
Control mode主要用于控制终端设备的硬件设置。利用termios结构的c_cflag的标志来加以控制。控制模式用在序列线连接到数据设备,也可以用在与终端设备的交谈。
一般来说,改变终端设备的组态要比使用termios的控制模式来改变行(lines)的行为来得容易。 
    • CBAUD :(不属于 POSIX) 波特率掩码 (4+1 位)。 
    • CBAUDEX :(不属于 POSIX) 扩展的波特率掩码 (1 位),包含在 CBAUD 中。 
    • (POSIX 规定波特率存储在 termios 结构中,并未精确指定它的位置,而是提供了函数 cfgetispeed() 和 cfsetispeed() 来存取它。一些系统使用 c_cflag 中 CBAUD 选择的位,其他系统使用单独的变量,例如 sg_ispeed 和 sg_ospeed 。) 
    • CSIZE:字符长度掩码(传送或接收字元时用的位数)。取值为 CS5(传送或接收字元时用5bits), CS6, CS7, 或 CS8。 
    • CSTOPB :设置两个停止位,而不是一个。 
    • CREAD :打开接受者。 
    • PARENB :允许输出产生奇偶信息以及输入的奇偶校验(启用同位产生与侦测)。 
    • PARODD :输入和输出是奇校验(使用奇同位而非偶同位)。 
    • HUPCL :在最后一个进程关闭设备后,降低 modem 控制线 (挂断)。(?) 
    • CLOCAL :忽略 modem 控制线。 
    • LOBLK :(不属于 POSIX) 从非当前 shell 层阻塞输出(用于 shl )。(?) 
    • CIBAUD :(不属于 POSIX) 输入速度的掩码。CIBAUD 各位的值与 CBAUD 各位相同,左移了 IBSHIFT 位。 
    • CRTSCTS :(不属于 POSIX) 启用 RTS/CTS (硬件) 流控制。
(四) c_lflag 标志常量: Local mode ( 局部模式)
Local mode主要用来控制终端设备不同的特色。利用termios结构里的c_lflag的标志来设定局部模式。
在巨集中有两个比较重要的标志:
1.ECHO:它可以让你阻止键入字元的回应。
2.ICANON(正规模式)标志,它可以对所接收的字元在两种不同的终端设备模式之间来回切换。 
  • ISIG:当接受到字符 INTR, QUIT, SUSP, 或 DSUSP 时,产生相应的信号。 
  • ICANON:启用标准模式 (canonical mode)。允许使用特殊字符 EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, 和 WERASE,以及按行的缓冲。 
  • XCASE:(不属于 POSIX; Linux 下不被支持) 如果同时设置了 ICANON,终端只有大写。输入被转换为小写,除了有前缀的字符。输出时,大写字符被前缀(某些系统指定的特定字符) ,小写字符被转换成大写。 
  • ECHO :回显输入字符。 
  • ECHOE :如果同时设置了 ICANON,字符 ERASE 擦除前一个输入字符,WERASE 擦除前一个词。 
  • ECHOK :如果同时设置了 ICANON,字符 KILL 删除当前行。 
  • ECHONL :如果同时设置了 ICANON,回显字符 NL,即使没有设置 ECHO。 
  • ECHOCTL :(不属于 POSIX) 如果同时设置了 ECHO,除了 TAB, NL, START, 和 STOP 之外的 ASCII 控制信号被回显为 ^X, 这里 X 是比控制信号大 0x40 的 ASCII 码。例如,字符 0x08 (BS) 被回显为 ^H。 
  • ECHOPRT :(不属于 POSIX) 如果同时设置了 ICANON 和 IECHO,字符在删除的同时被打印。 
  • ECHOKE :(不属于 POSIX) 如果同时设置了 ICANON,回显 KILL 时将删除一行中的每个字符,如同指定了 ECHOE 和 ECHOPRT 一样。 
  • DEFECHO :(不属于 POSIX) 只在一个进程读的时候回显。 
  • FLUSHO :(不属于 POSIX; Linux 下不被支持) 输出被刷新。这个标志可以通过键入字符 DISCARD 来开关。 
  • NOFLSH :禁止在产生 SIGINT, SIGQUIT 和 SIGSUSP 信号时刷新输入和输出队列,即关闭queue中的flush。 
  • TOSTOP :向试图写控制终端的后台进程组发送 SIGTTOU 信号(传送欲写入的信息到后台处理)。 
  • PENDIN :(不属于 POSIX; Linux 下不被支持) 在读入下一个字符时,输入队列中所有字符被重新输出。(bash 用它来处理 typeahead) 
  • IEXTEN :启用实现自定义的输入处理。这个标志必须与 ICANON 同时使用,才能解释特殊字符 EOL2,LNEXT,REPRINT 和 WERASE,IUCLC 标志才有效。 
(五)c_cc 数组: 特殊控制字元
可提供使用者设定一些特殊的功能,
如Ctrl+C的字元组合。
特殊控制字元主要是利用termios结构里c_cc的阵列成员来做设定。
c_cc阵列主要用于正规与非正规两种环境,但要注意的是正规与非正规不可混为一谈。
其定义了特殊的控制字符。符号下标 (初始值) 和意义为: 
  • VINTR:(003, ETX, Ctrl-C, or also 0177, DEL, rubout) 中断字符。发出 SIGINT 信号。当设置 ISIG 时可被识别,不再作为输入传递。 
  • VQUIT :(034, FS, Ctrl-) 退出字符。发出 SIGQUIT 信号。当设置 ISIG 时可被识别,不再作为输入传递。 
  • VERASE :(0177, DEL, rubout, or 010, BS, Ctrl-H, or also #) 删除字符。删除上一个还没有删掉的字符,但不删除上一个 EOF 或行首。当设置 ICANON 时可被识别,不再作为输入传递。 
  • VKILL :(025, NAK, Ctrl-U, or Ctrl-X, or also @) 终止字符。删除自上一个 EOF 或行首以来的输入。当设置 ICANON 时可被识别,不再作为输入传递。 
  • VEOF :(004, EOT, Ctrl-D) 文件尾字符。更精确地说,这个字符使得 tty 缓冲中的内容被送到等待输入的用户程序中,而不必等到 EOL。如果它是一行的第一个字符,那么用户程序的 read() 将返回 0,指示读到了 EOF。当设置 ICANON 时可被识别,不再作为输入传递。 
  • VMIN :非 canonical 模式读的最小字符数(MIN主要是表示能满足read的最小字元数)。 
  • VEOL :(0, NUL) 附加的行尾字符。当设置 ICANON 时可被识别。 
  • VTIME :非 canonical 模式读时的延时,以十分之一秒为单位。 
  • VEOL2 :(not in POSIX; 0, NUL) 另一个行尾字符。当设置 ICANON 时可被识别。 
  • VSWTCH :(not in POSIX; not supported under Linux; 0, NUL) 开关字符。(只为 shl 所用。) 
  • VSTART :(021, DC1, Ctrl-Q) 开始字符。重新开始被 Stop 字符中止的输出。当设置 IXON 时可被识别,不再作为输入传递。 
  • VSTOP :(023, DC3, Ctrl-S) 停止字符。停止输出,直到键入 Start 字符。当设置 IXON 时可被识别,不再作为输入传递。 
  • VSUSP :(032, SUB, Ctrl-Z) 挂起字符。发送 SIGTSTP 信号。当设置 ISIG 时可被识别,不再作为输入传递。 
  • VDSUSP :(not in POSIX; not supported under Linux; 031, EM, Ctrl-Y) 延时挂起信号。当用户程序读到这个字符时,发送 SIGTSTP 信号。当设置 IEXTEN 和 ISIG,并且系统支持作业管理时可被识别,不再作为输入传递。 
  • VLNEXT :(not in POSIX; 026, SYN, Ctrl-V) 字面上的下一个。引用下一个输入字符,取消它的任何特殊含义。当设置 IEXTEN 时可被识别,不再作为输入传递。 
  • VWERASE :(not in POSIX; 027, ETB, Ctrl-W) 删除词。当设置 ICANON 和 IEXTEN 时可被识别,不再作为输入传递。 
  • VREPRINT :(not in POSIX; 022, DC2, Ctrl-R) 重新输出未读的字符。当设置 ICANON 和 IEXTEN 时可被识别,不再作为输入传递。 
  • VDISCARD :(not in POSIX; not supported under Linux; 017, SI, Ctrl-O) 开关:开始/结束丢弃未完成的输出。当设置 IEXTEN 时可被识别,不再作为输入传递。 
  • VSTATUS :(not in POSIX; not supported under Linux; status request: 024, DC4, Ctrl-T). 
  • 这些符号下标值是互不相同的,除了 VTIME,VMIN 的值可能分别与 VEOL,VEOF 相同。 (在 non-canonical 模式下,特殊字符的含义更改为延时含义。MIN 表示应当被读入的最小字符数。TIME 是以十分之一秒为单位的计时器。如果同时设置了它们,read 将等待直到至少读入一个字符,一旦读入 MIN 个字符或者从上次读入字符开始经过了 TIME 时间就立即返回。如果只设置了 MIN,read 在读入 MIN 个字符之前不会返回。如果只设置了 TIME,read 将在至少读入一个字符,或者计时器超时的时候立即返回。如果都没有设置,read 将立即返回,只给出当前准备好的字符。)
  MIN与TIME组合有以下四种:
  • 1、 MIN = 0 , TIME =0
                  有READ立即回传
                  否则传回 0 ,不读取任何字元
    2、 MIN = 0 , TIME >0
                  READ 传回读到的字元,或在十分之一秒后传回TIME
           若来不及读到任何字元,则传回0
    3、 MIN > 0 , TIME =0
                  READ 会等待,直到MIN字元可读
    4、 MIN > 0 , TIME > 0
                  每一格字元之间计时器即会被启动
                  READ 会在读到MIN字元,传回值或TIME的字元计时(1/10秒)超过时将值传回
四、与此结构体相关的函数
(一)tcgetattr()
1.原型
int tcgetattr(int fd,struct termois & termios_p);
2.功能 
取得终端介质(fd)初始值,并把其值 赋给temios_p; 函数可以从后台进程中调用;但是,终端属性可能被后来的前台进程所改变。 

(二)tcsetattr() 
1.原型
int tcsetattr(int fd,int actions,const struct    termios *termios_p);
2.功能
设置与终端相关的参数 (除非需要底层支持却无法满足),使用 termios_p 引用的 termios 结构。optional_actions (tcsetattr函数的第二个参数)指定了什么时候改变会起作用: 
  • TCSANOW:改变立即发生 
  • TCSADRAIN:改变在所有写入 fd 的输出都被传输后生效。这个函数应当用于修改影响输出的参数时使用。(当前输出完成时将值改变
  • TCSAFLUSH :改变在所有写入 fd 引用的对象的输出都被传输后生效,所有已接受但未读入的输入都在改变发生前丢弃(同TCSADRAIN,但会舍弃当前所有值)。 
(三)tcsendbreak()
  传送连续的 0 值比特流,持续一段时间,如果终端使用异步串行数据传输的话。如果 duration 是 0,它至少传输 0.25 秒,不会超过 0.5 秒。如果 duration 非零,它发送的时间长度由实现定义。 
如果终端并非使用异步串行数据传输,tcsendbreak() 什么都不做。 
(四)tcdrain() 
等待直到所有写入 fd 引用的对象的输出都被传输。 
(五)tcflush() 
丢弃要写入 引用的对象,但是尚未传输的数据,或者收到但是尚未读取的数据,取决于 queue_selector 的值: 
  • TCIFLUSH :刷新收到的数据但是不读 
  • TCOFLUSH :刷新写入的数据但是不传送 
  • TCIOFLUSH :同时刷新收到的数据但是不读,并且刷新写入的数据但是不传送 
(六)tcflow() 
挂起 fd 引用的对象上的数据传输或接收,取决于 action 的值: 
  • TCOOFF :挂起输出 
  • TCOON :重新开始被挂起的输出 
  • TCIOFF :发送一个 STOP 字符,停止终端设备向系统传送数据 
  • TCION :发送一个 START 字符,使终端设备向系统传输数据 
打开一个终端设备时的默认设置是输入和输出都没有挂起。

(七)波特率函数
被用来获取和设置 termios 结构中,输入和输出波特率的值。新值不会马上生效,直到成功调用了 tcsetattr() 函数。
设置速度为 B0 使得 modem "挂机"。与 B38400 相应的实际比特率可以用 setserial(8) 调整。 
输入和输出波特率被保存于 termios 结构中。 
cfmakeraw 设置终端属性如下: 
            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;
1.cfgetospeed() 返回 termios_p 指向的 termios 结构中存储的输出波特率 
2.cfsetospeed() 设置 termios_p 指向的 termios 结构中存储的输出波特率为 speed。取值必须是以下常量之一: 
        B0        B50        B75        B110        B134        B150        B200        B300        B600        B1200        B1800        B2400        B4800        B9600        B19200        B38400        B57600        B115200        B230400
其中:零值 B0 用来中断连接。如果指定了 B0,不应当再假定存在连接。通常,这样将断开连接。CBAUDEX 是一个掩码,指示高于 POSIX.1 定义的速度的那一些 (57600 及以上)。因此,B57600 & CBAUDEX 为非零。 
3.cfgetispeed() 返回 termios 结构中存储的输入波特率。 
4.cfsetispeed() 设置 termios 结构中存储的输入波特率为 speed。如果输入波特率被设为0,实际输入波特率将等于输出波特率。 
五、RETURN VALUE 返回值
1.cfgetispeed() 返回 termios 结构中存储的输入波特率。 
2.cfgetospeed() 返回 termios 结构中存储的输出波特率。 
3.其他函数返回: 
  (1)0: 成功 
   (2)-1: 失败,
         并且为 errno 置值来指示错误。 
注意 tcsetattr() 返回成功,如果任何所要求的修改可以实现的话。因此,当进行多重修改时,应当在这个函数之后再次调用 tcgetattr() 来检测是否所有修改都成功实现。 
六、NOTES 注意
Unix V7 以及很多后来的系统有一个波特率的列表,在十四个值 B0, ..., B9600 之后可以看到两个常数 EXTA, EXTB ("External A" and "External B")。很多系统将这个列表扩展为更高的波特率。 
tcsendbreak 中非零的 duration 有不同的效果。SunOS 指定中断 duration*N 秒,其中 N 至少为 0.25,不高于 0.5 。Linux, AIX, DU, Tru64 发送 duration 微秒的 break 。FreeBSD, NetBSD, HP-UX 以及 MacOS 忽略 duration 的值。在 Solaris 和 Unixware 中, tcsendbreak 搭配非零的 duration 效果类似于 tcdrain。 
SEE ALSO 参见 
stty(1), setserial(8)
====
http://hao521lp.blog.163.com/blog/static/3459711720106235758618/

-----------------------------------------------------------------------------------

Name

termios, tcgetattr, tcsetattr, tcsendbreak, tcdrain, tcflush, tcflow, cfmakeraw, cfgetospeed, cfgetispeed, cfsetispeed, cfsetospeed, cfsetspeed - get and set terminal attributes, line control, get and set baud rate

Synopsis

#include <termios.h>
#include <unistd.h>

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

int tcsetattr(int fd, int optional_actions,
              const struct termios *termios_p);

int tcsendbreak(int fd, int duration);

int tcdrain(int fd);

int tcflush(int fd, int queue_selector);

int tcflow(int fd, int action);

void cfmakeraw(struct termios *termios_p);

speed_t cfgetispeed(const struct termios *termios_p);

speed_t cfgetospeed(const struct termios *termios_p);

int cfsetispeed(struct termios *termios_p, speed_t speed);

int cfsetospeed(struct termios *termios_p, speed_t speed);

int cfsetspeed(struct termios *termios_p, speed_t speed);
Feature Test Macro Requirements for glibc (see  feature_test_macros(7)):
cfsetspeed(),  cfmakeraw(): _BSD_SOURCE

Description

The termios functions describe a general terminal interface that is provided to control asynchronous communications ports.

The termios structure

Many of the functions described here have a  termios_p argument that is a pointer to a  termios structure. This structure contains at least the following members:
tcflag_t c_iflag;      /* input modes */
tcflag_t c_oflag;      /* output modes */
tcflag_t c_cflag;      /* control modes */
tcflag_t c_lflag;      /* local modes */
cc_t     c_cc[NCCS];   /* special characters */
The values that may be assigned to these fields are described below. In the case of the first four bit-mask fields, the definitions of some of the associated flags that may be set are only exposed if a specific feature test macro (see  feature_test_macros(7)) is defined, as noted in brackets ("[]").

In the descriptions below, "not in POSIX" means that the value is not specified in POSIX.1-2001, and "XSI" means that the value is specified in POSIX.1-2001 as part of the XSI extension.

c_iflag flag constants:

IGNBRK

Ignore BREAK condition on input.

BRKINT

If IGNBRK is set, a BREAK is ignored. If it is not set but BRKINT is set, then a BREAK causes the input and output queues to be flushed, and if the terminal is the controlling terminal of a foreground process group, it will cause a SIGINT to be sent to this foreground process group. When neither IGNBRK nor BRKINT are set, a BREAK reads as a null byte ('\0'), except when PARMRK is set, in which case it reads as the sequence \377 \0 \0.

IGNPAR

Ignore framing errors and parity errors.

PARMRK

If IGNPAR is not set, prefix a character with a parity error or framing error with \377 \0. If neither IGNPAR nor PARMRK is set, read a character with a parity error or framing error as \0.

INPCK

Enable input parity checking.

ISTRIP

Strip off eighth bit.

INLCR

Translate NL to CR on input.

IGNCR

Ignore carriage return on input.

ICRNL

Translate carriage return to newline on input (unless IGNCR is set).

IUCLC

(not in POSIX) Map uppercase characters to lowercase on input.

IXON

Enable XON/XOFF flow control on output.

IXANY

(XSI) Typing any character will restart stopped output. (The default is to allow just the START character to restart output.)

IXOFF

Enable XON/XOFF flow control on input.

IMAXBEL
(not in POSIX) Ring bell when input queue is full. Linux does not implement this bit, and acts as if it is always set.
IUTF8 (since Linux 2.6.4)
(not in POSIX) Input is UTF8; this allows character-erase to be correctly performed in cooked mode.
c_oflag flag constants defined in POSIX.1:
OPOST

Enable implementation-defined output processing.

The remaining  c_oflag flag constants are defined in POSIX.1-2001, unless marked otherwise.
OLCUC

(not in POSIX) Map lowercase characters to uppercase on output.

ONLCR

(XSI) Map NL to CR-NL on output.

OCRNL

Map CR to NL on output.

ONOCR

Don't output CR at column 0.

ONLRET

Don't output CR.

OFILL

Send fill characters for a delay, rather than using a timed delay.

OFDEL

(not in POSIX) Fill character is ASCII DEL (0177). If unset, fill character is ASCII NUL ('\0'). (Not implemented on Linux.)

NLDLY

Newline delay mask. Values are NL0 and NL1. [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]

CRDLY

Carriage return delay mask. Values are CR0CR1CR2, or CR3. [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]

TABDLY

Horizontal tab delay mask. Values are TAB0TAB1TAB2TAB3 (or XTABS). A value of TAB3, that is, XTABS, expands tabs to spaces (with tab stops every eight columns). [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]

BSDLY

Backspace delay mask. Values are BS0 or BS1. (Has never been implemented.) [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]

VTDLY

Vertical tab delay mask. Values are VT0 or VT1.

FFDLY

Form feed delay mask. Values are FF0 or FF1. [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]

c_cflag flag constants:
CBAUD

(not in POSIX) Baud speed mask (4+1 bits). [requires _BSD_SOURCE or _SVID_SOURCE]

CBAUDEX
(not in POSIX) Extra baud speed mask (1 bit), included in  CBAUD. [requires  _BSD_SOURCE or  _SVID_SOURCE]

(POSIX says that the baud speed is stored in the termios structure without specifying where precisely, and provides cfgetispeed() and cfsetispeed() for getting at it. Some systems use bits selected by CBAUD in c_cflag, other systems use separate fields, for example, sg_ispeed and sg_ospeed.)

CSIZE

Character size mask. Values are CS5CS6CS7, or CS8.

CSTOPB

Set two stop bits, rather than one.

CREAD

Enable receiver.

PARENB

Enable parity generation on output and parity checking for input.

PARODD

If set, then parity for input and output is odd; otherwise even parity is used.

HUPCL

Lower modem control lines after last process closes the device (hang up).

CLOCAL

Ignore modem control lines.

LOBLK

(not in POSIX) Block output from a noncurrent shell layer. For use by shl (shell layers). (Not implemented on Linux.)

CIBAUD

(not in POSIX) Mask for input speeds. The values for the CIBAUD bits are the same as the values for the CBAUD bits, shifted left IBSHIFT bits. [requires _BSD_SOURCE or_SVID_SOURCE] (Not implemented on Linux.)

CMSPAR

(not in POSIX) Use "stick" (mark/space) parity (supported on certain serial devices): if PARODD is set, the parity bit is always 1; if PARODD is not set, then the parity bit is always 0). [requires _BSD_SOURCE or _SVID_SOURCE]

CRTSCTS
(not in POSIX) Enable RTS/CTS (hardware) flow control. [requires  _BSD_SOURCE or  _SVID_SOURCE]
c_lflag flag constants:
ISIG

When any of the characters INTR, QUIT, SUSP, or DSUSP are received, generate the corresponding signal.

ICANON

Enable canonical mode (described below).

XCASE

(not in POSIX; not supported under Linux) If ICANON is also set, terminal is uppercase only. Input is converted to lowercase, except for characters preceded by \. On output, uppercase characters are preceded by \ and lowercase characters are converted to uppercase. [requires _BSD_SOURCE or _SVID_SOURCE or _XOPEN_SOURCE]

ECHO

Echo input characters.

ECHOE

If ICANON is also set, the ERASE character erases the preceding input character, and WERASE erases the preceding word.

ECHOK

If ICANON is also set, the KILL character erases the current line.

ECHONL

If ICANON is also set, echo the NL character even if ECHO is not set.

ECHOCTL
(not in POSIX) If  ECHO is also set, terminal special characters other than TAB, NL, START, and STOP are echoed as  ^X, where X is the character with ASCII code 0x40 greater than the special character. For example, character 0x08 (BS) is echoed as  ^H. [requires  _BSD_SOURCE or  _SVID_SOURCE]
ECHOPRT
(not in POSIX) If  ICANON and  IECHO are also set, characters are printed as they are being erased. [requires  _BSD_SOURCE or  _SVID_SOURCE]
ECHOKE

(not in POSIX) If ICANON is also set, KILL is echoed by erasing each character on the line, as specified by ECHOE and ECHOPRT. [requires _BSD_SOURCE or_SVID_SOURCE]

DEFECHO
(not in POSIX) Echo only when a process is reading. (Not implemented on Linux.)
FLUSHO

(not in POSIX; not supported under Linux) Output is being flushed. This flag is toggled by typing the DISCARD character. [requires _BSD_SOURCE or _SVID_SOURCE]

NOFLSH

Disable flushing the input and output queues when generating signals for the INT, QUIT, and SUSP characters.

TOSTOP

Send the SIGTTOU signal to the process group of a background process which tries to write to its controlling terminal.

PENDIN

(not in POSIX; not supported under Linux) All characters in the input queue are reprinted when the next character is read. (bash(1) handles typeahead this way.) [requires_BSD_SOURCE or _SVID_SOURCE]

IEXTEN

Enable implementation-defined input processing. This flag, as well as ICANON must be enabled for the special characters EOL2, LNEXT, REPRINT, WERASE to be interpreted, and for the IUCLC flag to be effective.

The  c_cc array defines the terminal special characters. The symbolic indices (initial values) and meaning are:
VDISCARD
(not in POSIX; not supported under Linux; 017, SI, Ctrl-O) Toggle: start/stop discarding pending output. Recognized when  IEXTEN is set, and then not passed as input.
VDSUSP

(not in POSIX; not supported under Linux; 031, EM, Ctrl-Y) Delayed suspend character (DSUSP): send SIGTSTP signal when the character is read by the user program. Recognized when IEXTEN and ISIG are set, and the system supports job control, and then not passed as input.

VEOF

(004, EOT, Ctrl-D) End-of-file character (EOF). More precisely: this character causes the pending tty buffer to be sent to the waiting user program without waiting for end-of-line. If it is the first character of the line, the read(2) in the user program returns 0, which signifies end-of-file. Recognized when ICANON is set, and then not passed as input.

VEOL

(0, NUL) Additional end-of-line character (EOL). Recognized when ICANON is set.

VEOL2

(not in POSIX; 0, NUL) Yet another end-of-line character (EOL2). Recognized when ICANON is set.

VERASE

(0177, DEL, rubout, or 010, BS, Ctrl-H, or also #) Erase character (ERASE). This erases the previous not-yet-erased character, but does not erase past EOF or beginning-of-line. Recognized when ICANON is set, and then not passed as input.

VINTR

(003, ETX, Ctrl-C, or also 0177, DEL, rubout) Interrupt character (INTR). Send a SIGINT signal. Recognized when ISIG is set, and then not passed as input.

VKILL

(025, NAK, Ctrl-U, or Ctrl-X, or also @) Kill character (KILL). This erases the input since the last EOF or beginning-of-line. Recognized when ICANON is set, and then not passed as input.

VLNEXT

(not in POSIX; 026, SYN, Ctrl-V) Literal next (LNEXT). Quotes the next input character, depriving it of a possible special meaning. Recognized when IEXTEN is set, and then not passed as input.

VMIN

Minimum number of characters for noncanonical read (MIN).

VQUIT

(034, FS, Ctrl-\) Quit character (QUIT). Send SIGQUIT signal. Recognized when ISIG is set, and then not passed as input.

VREPRINT
(not in POSIX; 022, DC2, Ctrl-R) Reprint unread characters (REPRINT). Recognized when  ICANON and  IEXTEN are set, and then not passed as input.
VSTART

(021, DC1, Ctrl-Q) Start character (START). Restarts output stopped by the Stop character. Recognized when IXON is set, and then not passed as input.

VSTATUS
(not in POSIX; not supported under Linux; status request: 024, DC4, Ctrl-T). Status character (STATUS). Display status information at terminal, including state of foreground process and amount of CPU time it has consumed. Also sends a  SIGINFO signal (not supported on Linux) to the foreground process group.
VSTOP

(023, DC3, Ctrl-S) Stop character (STOP). Stop output until Start character typed. Recognized when IXON is set, and then not passed as input.

VSUSP

(032, SUB, Ctrl-Z) Suspend character (SUSP). Send SIGTSTP signal. Recognized when ISIG is set, and then not passed as input.

VSWTCH

(not in POSIX; not supported under Linux; 0, NUL) Switch character (SWTCH). Used in System V to switch shells in shell layers, a predecessor to shell job control.

VTIME

Timeout in deciseconds for noncanonical read (TIME).

VWERASE
(not in POSIX; 027, ETB, Ctrl-W) Word erase (WERASE). Recognized when  ICANON and  IEXTEN are set, and then not passed as input.
An individual terminal special character can be disabled by setting the value of the corresponding  c_cc element to  _POSIX_VDISABLE.

The above symbolic subscript values are all different, except that VTIMEVMIN may have the same value as VEOLVEOF, respectively. In noncanonical mode the special character meaning is replaced by the timeout meaning. For an explanation of VMIN and VTIME, see the description of noncanonical mode below.

Retrieving and changing terminal settings

tcgetattr() gets the parameters associated with the object referred by  fd and stores them in the  termios structure referenced by  termios_p. This function may be invoked from a background process; however, the terminal attributes may be subsequently changed by a foreground process.

tcsetattr() sets the parameters associated with the terminal (unless support is required from the underlying hardware that is not available) from the termios structure referred to bytermios_poptional_actions specifies when the changes take effect:

TCSANOW
the change occurs immediately.
TCSADRAIN
the change occurs after all output written to  fd has been transmitted. This function should be used when changing parameters that affect output.
TCSAFLUSH
the change occurs after all output written to the object referred by  fd has been transmitted, and all input that has been received but not read will be discarded before the change is made.

Canonical and noncanonical mode

The setting of the  ICANON canon flag in  c_lflag determines whether the terminal is operating in canonical mode ( ICANON set) or noncanonical mode ( ICANON unset). By default,  ICANON set.

In canonical mode:

*

Input is made available line by line. An input line is available when one of the line delimiters is typed (NL, EOL, EOL2; or EOF at the start of line). Except in the case of EOF, the line delimiter is included in the buffer returned by read(2).

*

Line editing is enabled (ERASE, KILL; and if the IEXTEN flag is set: WERASE, REPRINT, LNEXT). A read(2) returns at most one line of input; if the read(2) requested fewer bytes than are available in the current line of input, then only as many bytes as requested are read, and the remaining characters will be available for a future read(2).

In noncanonical mode input is available immediately (without the user having to type a line-delimiter character), and line editing is disabled. The settings of MIN ( c_cc[VMIN]) and TIME ( c_cc[VTIME]) determine the circumstances in which a  read(2) completes; there are four distinct cases:
*

MIN == 0; TIME == 0: If data is available, read(2) returns immediately, with the lesser of the number of bytes available, or the number of bytes requested. If no data is available,read(2) returns 0.

*

MIN > 0; TIME == 0: read(2) blocks until the lesser of MIN bytes or the number of bytes requested are available, and returns the lesser of these two values.

*

MIN == 0; TIME > 0: TIME specifies the limit for a timer in tenths of a second. The timer is started when read(2) is called. read(2) returns either when at least one byte of data is available, or when the timer expires. If the timer expires without any input becoming available, read(2) returns 0.

*

MIN > 0; TIME > 0: TIME specifies the limit for a timer in tenths of a second. Once an initial byte of input becomes available, the timer is restarted after each further byte is received. read(2) returns either when the lesser of the number of bytes requested or MIN byte have been read, or when the inter-byte timeout expires. Because the timer is only started after the initial byte becomes available, at least one byte will be read.

Raw mode

cfmakeraw() sets the terminal to something like the "raw" mode of the old Version 7 terminal driver: input is available character by character, echoing is disabled, and all special processing of terminal input and output characters is disabled. The terminal attributes are set 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;

Line control

tcsendbreak() transmits a continuous stream of zero-valued bits for a specific duration, if the terminal is using asynchronous serial data transmission. If  duration is zero, it transmits zero-valued bits for at least 0.25 seconds, and not more that 0.5 seconds. If  duration is not zero, it sends zero-valued bits for some implementation-defined length of time.

If the terminal is not using asynchronous serial data transmission, tcsendbreak() returns without taking any action.

tcdrain() waits until all output written to the object referred to by fd has been transmitted.

tcflush() discards data written to the object referred to by fd but not transmitted, or data received but not read, depending on the value of queue_selector:

TCIFLUSH
flushes data received but not read.
TCOFLUSH
flushes data written but not transmitted.
TCIOFLUSH
flushes both data received but not read, and data written but not transmitted.
tcflow() suspends transmission or reception of data on the object referred to by  fd, depending on the value of  action:
TCOOFF

suspends output.

TCOON

restarts suspended output.

TCIOFF

transmits a STOP character, which stops the terminal device from transmitting data to the system.

TCION

transmits a START character, which starts the terminal device transmitting data to the system.

The default on open of a terminal file is that neither its input nor its output is suspended.

Line speed

The baud rate functions are provided for getting and setting the values of the input and output baud rates in the  termios structure. The new values do not take effect until tcsetattr() is successfully called.

Setting the speed to B0 instructs the modem to "hang up". The actual bit rate corresponding to B38400 may be altered with setserial(8).

The input and output baud rates are stored in the termios structure.

cfgetospeed() returns the output baud rate stored in the termios structure pointed to by termios_p.

cfsetospeed() sets the output baud rate stored in the termios structure pointed to by termios_p to speed, which must be one of these constants:

B0

B50

B75

B110

B134

B150

B200

B300

B600

B1200

B1800

B2400

B4800

B9600

B19200

B38400

B57600

B115200

B230400

The zero baud rate,  B0, is used to terminate the connection. If B0 is specified, the modem control lines shall no longer be asserted. Normally, this will disconnect the line. CBAUDEX is a mask for the speeds beyond those defined in POSIX.1 (57600 and above). Thus,  B57600 &  CBAUDEX is nonzero.

cfgetispeed() returns the input baud rate stored in the termios structure.

cfsetispeed() sets the input baud rate stored in the termios structure to speed, which must be specified as one of the Bnnn constants listed above for cfsetospeed(). If the input baud rate is set to zero, the input baud rate will be equal to the output baud rate.

cfsetspeed() is a 4.4BSD extension. It takes the same arguments as cfsetispeed(), and sets both input and output speed.

Return Value

cfgetispeed() returns the input baud rate stored in the termios structure.

cfgetospeed() returns the output baud rate stored in the termios structure.

All other functions return:

0

on success.

-1

on failure and set errno to indicate the error.

Note that  tcsetattr() returns success if  any of the requested changes could be successfully carried out. Therefore, when making multiple changes it may be necessary to follow this call with a further call to  tcgetattr() to check that all changes have been performed successfully.

Conforming To

tcgetattr(), tcsetattr(), tcsendbreak(), tcdrain(), tcflush(), tcflow(), cfgetispeed(), cfgetospeed(), cfsetispeed(), and cfsetospeed() are specified in POSIX.1-2001.

cfmakeraw() and cfsetspeed() are nonstandard, but available on the BSDs.

Notes

UNIX V7 and several later systems have a list of baud rates where after the fourteen values B0, ..., B9600 one finds the two constants EXTA, EXTB ("External A" and "External B"). Many systems extend the list with much higher baud rates.

The effect of a nonzero duration with tcsendbreak() varies. SunOS specifies a break of duration * N seconds, where N is at least 0.25, and not more than 0.5. Linux, AIX, DU, Tru64 send a break of duration milliseconds. FreeBSD and NetBSD and HP-UX and MacOS ignore the value of duration. Under Solaris and UnixWare, tcsendbreak() with nonzero duration behaves like tcdrain().

====
http://linux.die.net/man/3/termios

你可能感兴趣的:(串口程序设计——struct termios结构体)