tcgetattr学习

一、函数名称:

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

二、函数功能:

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

用于获取与终端相关的参数,提供异步通讯接口

三、头文件

termios.h
unistd.h


四、返回值

0:成功
-1:错误,

五、参数说明

fd:文件描述符
struct termios *termios_p:返回值保留在termios结构体中:
           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 */                      控制字符,保存中断驱动程序中的特殊字符

六、示例程序:

 1     #include <stdio.h>
 2     #include <termios.h>
 3     #include <unistd.h>
 4     #include <errno.h>
 5 
 6     int main(void)
 7     {
 8         struct termios term; //get terminal interface
 9         int err;
10 
11         if(tcgetattr(STDIN_FILENO, &term)==-1)
12         {
13             perror("Cannot get standard input description.");
14             return 1;
15         }
16 
17         term.c_cc[VEOF] = (cc_t)0x07;
18         err = tcsetattr(STDIN_FILENO, TCSAFLUSH, &term);
19         if(err==-1 && err==EINTR)
20         {
21             perror("Failed to change EOF character.");
22             return 1;
23         }
24 
25         return 0;
26     }
运行后可以使ctrl+D不起作用,使用ctrl+G替代ctrl+D.


七、补充:

函数tcsetattr 可以设置串口的结构属性,tcgetatt( ) 可以得到串口的结构属性。在termios 结构中,最重要的是c_cflag,用户通过对其进行赋值可以实现串口波特率、数据位、停止位、奇偶校验位等参数的设置。c_cc 数组中的两个变量VMIN 和VTIME 判断是否返回输入,c _cc[VTIME]设定字节输入时间计时器,c _cc[VMIN]设定满足读取功能的最低接收字节数。这两个变量的值要设定合理,才能保证串口的通信成功率。
http://www.hqew.com/tech/sheji/660631.html
无欲速,无见小利。欲速,则不达;见小利,则大事不成。
原文地址:https://www.cnblogs.com/ch122633/p/7363248.html