我在管理从 Arduino 单元进入 linux 串行端口的数据时遇到了问题。
基本上,我有一个可以读取和打印(或只是存储)的工作代码,但它是为 Windows 平台编写的:
状态是 COMSTAT 类型
int SerialPort::readSerialPort(char *buffer, unsigned int buf_size)
{
DWORD bytesRead;
unsigned int toRead = 0;
Sleep(500);
ClearCommError(this->handler, &this->errors, &this->status);
if (this->status.cbInQue > 0) { //if there's something to read
if (this->status.cbInQue > buf_size) {//if there's something to read&bigger than buffer size
toRead = buf_size; //read as much as buffer alows
}
else toRead = this->status.cbInQue; //else just read as much as there is
}
if (ReadFile(this->handler, buffer, toRead, &bytesRead, NULL))
return bytesRead; //return read data
return 0;//return 0 if nothing is there.
}
除了 Windows 函数 Sleep() 之外,我想知道是否有一个等效的 linux 函数用于 status.cbInQue 以了解是否有任何数据可以在端口中读取。现在我只是继续阅读,没有检查,而且我经常在程序的后面没有打印任何东西。
TLDR:是否有适用于 Linux 的 cbInQue 等效项?
谢谢
是的,您将需要您的文件描述符,然后使用 FIONREAD
来查看是否有可用的内容。
像下面这样的东西应该可以工作:
int available;
if( ioctl( fd, FIONREAD, &available ) < 0 ) {
// Error handling here
}
我是一名优秀的程序员,十分优秀!