检查串行端口Linux中是否有传入数据(cbInQue for linux)

Check if there's incoming data in serial port linux (cbInQue for linux)

本文关键字:数据 cbInQue for linux Linux 串行端口 是否 检查      更新时间:2023-10-16

我在管理从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.
}

除了 Sleep(( 即 windows 函数之外,我想知道是否有一个等效的 linux 函数用于 status.cbInQue 以了解是否有任何数据准备好在端口中读取。 现在我只是继续阅读,没有检查,而且通常我在程序后面什么也没打印出来。

TLDR:Linux有cbInQue等价物吗?

谢谢

是的,您将需要文件描述符,然后使用FIONREAD查看是否有任何可用内容。

类似以下内容的内容应该有效:

int available;
if( ioctl( fd, FIONREAD, &available ) < 0 ) {
// Error handling here
}