This commit is contained in:
Alvin-lyq 2026-05-08 10:27:52 +08:00
parent 80711d985c
commit 82c56067de

View File

@ -50,6 +50,10 @@ bool CANDriver::open(const std::string& interface)
return false;
}
// 增大接收缓冲区,防止高流量时丢帧
int buf_size = 1024 * 1024; // 1MB
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &buf_size, sizeof(buf_size));
// 设置为非阻塞
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
@ -159,8 +163,17 @@ void CANDriver::receiveThreadFunc()
continue;
}
// 读取所有缓冲的帧,避免帧堆积丢失
while (running)
{
ssize_t nbytes = read(sockfd, &raw_frame, sizeof(raw_frame));
if (nbytes == sizeof(raw_frame) && callback)
if (nbytes != sizeof(raw_frame))
{
// 没有更多数据或出错,退出内层循环
break;
}
if (callback)
{
CANFrame frame;
frame.id = raw_frame.can_id & CAN_EFF_MASK;
@ -173,4 +186,5 @@ void CANDriver::receiveThreadFunc()
callback(frame, userData);
}
}
}
}