pvh*_*987 13 c unix timeout tty
我正在使用文件描述符和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秒超时?
任何帮助表示赞赏.提前致谢 :-)
Ada*_*eld 19
是的,使用select(2)
.传入一个文件描述符集,其中只包含读取集中的fd和空写入/异常集,并传入适当的超时.例如:
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
}
Run Code Online (Sandbox Code Playgroud)