如何停止C ++阻止读取调用

时间:2020-06-29 14:49:27

标签: c++ can-bus

我正在GNU / Linux中的SocketCAN和C ++下读取CAN-BUS通信。我发现read调用受阻,并且我想找出当我不想继续阅读时如何正确停止程序的方法。

当然,如果我从终端上调用了程序,我可能会打Ctrl+C,但是关键是要找到一种在满足某些条件(例如记录5秒,或发生某些事件(例如,引发一个标志)。超时可能会起作用,或者类似信号,但我不知道如何正确执行。

// Read (blocking)
nbytes = read(s, &frame, sizeof(struct can_frame));

2 个答案:

答案 0 :(得分:3)

你没有。

使用类似selectepoll的方法来确定套接字在开始read之前是否有活动 。然后它实际上不会阻塞。

select / epoll调用本身是阻塞的,但是可以设置超时,以便您始终拥有一条逃生路线(或者,对于epoll而言,可爱的{ {1}},以立即触发突破。

答案 1 :(得分:1)

读取始终处于阻塞状态...您只想在数据正在等待时才读取...,因此请考虑首先在套接字上进行一次轮询,以查看数据是否可用,然后再进行读取。您可以循环进行民意测验,直到您不再想要阅读为止...

bool pollIn(int fd)
{
    bool returnValue{false};
    struct pollfd *pfd;
    pfd = calloc(1, sizeof(struct pollfd));
    pfd.fd = fd;
    pfd.events = POLLIN;

    int pollReturn{-1};
    pollReturn = poll(pfd, 1, 0);

    if (pollReturn > 0)
    {
        if (pfd.revents & POLLIN)
        {
            returnValue = true;
        }
    }
    free(pfd);
    return(returnValue);
}

如果套接字文件描述符中有数据正在等待,以上内容应返回。

while(!exitCondition)
{
  if(pollIn(fd))
  {
    nbytes = read(fd, &frame, sizeof(struct can_frame));
    // other stuff you need to do with your read
  }
}