我正在阅读GNU/Linux中SocketCAN和C++下的CAN总线流量。 我发现read调用被阻塞了,我很难弄清楚当我不想继续读取时如何正确地停止我的程序。
当然,如果我已经从终端调用了程序,我可以点击Ctrl+C
,但关键是要找到一种方法,在满足某些条件时(例如,记录5秒,或者发生某些事件时,例如升起一个标志)以编程方式执行该操作。 一个超时可以工作,或类似于一个信号,但我不知道如何正确地做它。
// Read (blocking)
nbytes = read(s, &frame, sizeof(struct can_frame));
你不知道。
使用类似select
或epoll
的方法在开始read
之前确定套接字是否具有activity。 那么它实际上不会阻塞。
select
/epoll
调用本身是阻塞的,但是可以给它一个超时,这样您就始终有一条逃逸路由。
读取总是被阻止。。。 您只想在数据等待时读取。。。 因此,请考虑首先在套接字上进行轮询,以查看数据是否可用,如果可用,然后读取它。 你可以循环进行投票,直到你不再想读了。。。
bool pollIn(int fd)
{
bool returnValue{false};
int pollReturn{-1};
pollReturn = poll(fd, 1, 0);
if (pollReturn > 0)
{
if (this->pollFD.revents & POLLIN)
{
returnValue = true;
}
}
return(returnValue);
}
如果有数据在套接字文件描述符处等待,则应返回上述结果。
while(!exitCondition)
{
if(pollIn(fd))
{
nbytes = read(fd, &frame, sizeof(struct can_frame));
// other stuff you need to do with your read
}
}