我正在使用文件描述符和posix/unix read()函数从C++中的串口读取字节.在这个例子中,我从串口读取1个字节(为了清楚起见,省略了波特率设置和类似内容):
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果连接到/ dev/ttyS0的设备未发送任何信息,程序将挂起.如何设置超时?
我试过像这样设置一个时间:
struct termios options;
tcgetattr(fd, &options);
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
tcsetattr(fd, TCSANOW, &options);
Run Code Online (Sandbox Code Playgroud)
我认为它应该给1秒超时,但它没有任何区别.我想我误解了VMIN和VTIME.什么是VMIN和VTIME用于?
然后我搜索了网络,发现有人在谈论select()函数.这是解决方案,如果是这样,如何将其应用于上面的程序以使1秒超时?
任何帮助表示赞赏.提前致谢 :-)