定位Linux下写句柄错误问题

编写代码时发现对于以下can 写资源句柄时出现的错误不是很能分析,但是如果将错误码打印出来后,清晰了很多,并且还可以查看。

int Can::Write(const struct can_frame *send_frame)
{ 
  int result;
  std::cout << "before write s_ :" << s_  << std::endl;
  // write
  try{
    result = write(s_, send_frame, sizeof(*send_frame));
    if (result < 0)
    {
      std::cerr <<"Error writing to CAN socket: " << strerror(errno) << std::endl;
      std::cout << "Data size: " << sizeof(*send_frame) << std::endl;
      std::cout << "Socket descriptor: " << s_ << std::endl;
      std::cout << "write result: " << result << std::endl;
      // 错误类型: ENETDOWN
      // 说明: can 接口已关闭
      // 复现方法: 直接手动关闭can, command: sudo ip link set can0 down
      // 目前这种错误不能恢复
      
      // 错误类型: Bad file descriptor
      // 说明: 无效的文件描述符
      // 复现方法:程序中close socket can
      if (errno == EBADF) {
        // CAN 接口已关闭
        cout << "can socket closed" << endl;
        if(reconnectionsTimes <= Setting::MaxCanReconnections)
        {
          if(!ReinitializeCanBus())
          {
            ++reconnectionsTimes;
            std::cerr << "Failed to reinitialize CAN bus, reconnectionsTimes: " << reconnectionsTimes << std::endl;
            return result;
          }else
          {
            cout << "reinitialize CAN bus success! " << endl;
            reconnectionsTimes = 0;
          }
        }
      }
    }
  }catch(std::exception& e)
  {
     std::cout << "Can write error: " << e.what() << std::endl;
  }
  return result;
}

定位Linux下写句柄错误问题_第1张图片
我开发机上错误码对应的位置在如下所述位置。
定位Linux下写句柄错误问题_第2张图片

你可能感兴趣的:(linux)