Unix CAN套接字不等待消息

时间:2019-10-16 11:40:09

标签: c++ linux sockets unix can-bus

我有一个如下创建的unix CAN套接字:

#include <linux/can.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>

int main() {

    struct can_frame _msg;

    struct sockaddr_can addr;
    struct ifreq ifr;

    int _sock_fd = socket(PF_CAN, SOCK_RAW, CAN_RAW);

    if (_sock_fd < 0) {
    }

    strcpy(ifr.ifr_name, "can0");
    if (0 != ioctl(_sock_fd, SIOCGIFINDEX, &ifr)) {
    }
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;

    fcntl(_sock_fd, F_SETFL, O_NONBLOCK);

    if (0 != bind(_sock_fd, (struct sockaddr*)&addr, sizeof(addr))) {
    }

    while (1) {
      ssize_t size = 0;
      ssize_t tmp = 0;
      while (size < sizeof(struct can_frame)) {
        tmp = read(_sock_fd, &_msg, sizeof(struct can_frame));
        if (tmp <= 0) {
            printf("0\n");
        }
        size += tmp;
    }
    printf("%x %x %lx\n", _msg.can_id, _msg.can_dlc, *((uint64_t*)_msg.data));

  }
  return 0;
}


在此套接字上执行read时,即使发件人未发送任何内容,我也总是会立即收到消息。 read始终读取最新收到的邮件的副本,而不是等待下一封。我的阅读如下:

    size_t size = 0;
    while (size < sizeof(struct can_frame)) size += read(_sock_fd, &_msg, sizeof(struct can_frame));

这让我感到困惑,为什么read总是返回重复的消息,等待下一条消息。如果我与yeld一起循环调用read函数,那么当发件人只发送一个消息时,它会产生数百万条相同消息的重复消息:candump实用程序以正确的方式显示接收到的消息。为什么会有这种行为?

0 个答案:

没有答案