我如何能实现读(超时)串行端口(C / C ++)阅读时 [英] How can I implement timeout for read() when reading from a serial port (C/C++)

查看:127
本文介绍了我如何能实现读(超时)串行端口(C / C ++)阅读时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中使用文件描述符和POSIX串口读取字节/ UNIX的read()函数。

I am reading bytes from a serial port in C++ using a file descriptor and the posix/unix read() function. In this example, I am reading 1 byte from the serial port (baud rate settings and similiar are omitted for clarity):

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

int main(void)
{
   int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
   char buf[1];
   int bytesRead = read(fd, buf, 1);
   close(fd);
   return 0;
}

如果连接到/ dev / ttyS0的速率设备不发送任何信息,程序将挂起。如何设置超时?

If the device connected to /dev/ttyS0 does not send any information, the program will hang. How can I set a timeout?

我已经尝试设置超时是这样的:

I have tried setting a time out like this:

struct termios options;
tcgetattr(fd, &options);
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
tcsetattr(fd, TCSANOW, &options);

我认为这是应该得到1-秒超时,但它并没有区别。我想我误会了VMIN和VTIME。什么是VMIN和VTIME用的?

I thought it was supposed to give 1 second timeout, but it makes no difference. I think I have misunderstood VMIN and VTIME. What is VMIN and VTIME used for?

然后我在网上搜索,发现有人谈论select()函数。是该解决方案,如果是这样,怎么总会有它应用到上面的程序使之达到1秒超时?

Then I searched the web and found somebody talking about the select() function. Is that the solution and if so, how would one apply that to the program above to make 1 second timeout?

任何帮助是AP preciated。在此先感谢: - )

Any help is appreciated. Thanks in advance :-)

推荐答案

是,使用 选择( 2) 。通过在只包含您在读取设置和空写/异常套FD文件描述符集,并通过在适当的超时。例如:

Yes, use select(2). Pass in a file descriptor set containing just your fd in the read set and empty write/exception sets, and pass in an appropriate timeout. For example:

int fd = open(...);

// Initialize file descriptor sets
fd_set read_fds, write_fds, except_fds;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
FD_ZERO(&except_fds);
FD_SET(fd, &read_fds);

// Set timeout to 1.0 seconds
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;

// Wait for input to become ready or until the time out; the first parameter is
// 1 more than the largest file descriptor in any of the sets
if (select(fd + 1, &read_fds, &write_fds, &except_fds, &timeout) == 1)
{
    // fd is ready for reading
}
else
{
    // timeout or error
}

这篇关于我如何能实现读(超时)串行端口(C / C ++)阅读时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆