加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

Linux串行端口:使用超时阻止读取

发布时间:2020-12-14 01:04:30 所属栏目:Linux 来源:网络整理
导读:我已经研究了许多有用的线程和一些教程,但我仍然遇到一些应该非常简单的问题.这里参考一些我已经阅读过的主题: How to implement a timeout in read function call? how to open,read,and write from serial port in C 无论如何,我有点问题.如果我收到数据,
我已经研究了许多有用的线程和一些教程,但我仍然遇到一些应该非常简单的问题.这里参考一些我已经阅读过的主题:

How to implement a timeout in read function call?

how to open,read,and write from serial port in C

无论如何,我有点问题.如果我收到数据,我的代码工作正常.如果我不这样做,read()函数会停止并且退出程序的唯一方法是使用kill -9(注意:我使用信号处理来向读取串行数据的线程发出信号以终止.这不是罪魁祸首,即使我已经删除了我的信号处理,read()调用仍然停止.我想要做的是读取一次阻塞和读取一个块(因此节省CPU使用率),但是如果读取没有数据,我就不会超时.

以下是我正在应用于端口的设置:

struct termios serial_struct;
serial_struct.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
serial_struct.c_iflag = IGNPAR;
serial_struct.c_oflag = 0;
serial_struct.c_lflag = 0;
serial_struct.c_cc[VTIME] = 1;  // timeout after .1s that isn't working
serial_struct.c_cc[VMIN] = 64;  // want to read a chunk of 64 bytes at a given time

然后我使用tcsetattr()设置这些设置,并确认端口通过tcgetattr()接收设置.我认为我的设置可能有冲突,因为我的读取似乎是阻塞并等待直到收到64个字节,但是对于超时没有做任何事情.我知道我可以使用select()来处理超时,但我希望避免多个系统调用.

一如既往,感谢您的帮助.

解决方法

从 man 3 termios开始:

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.

请注意,在收到至少一个字节的数据之前,定时器不会启动.在接收到第一个数据字节后,如果在接收连续数据字节之间存在TIME十分之一秒的间隔,则读取将超时.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读