我正在尝试使用标准Windows库编写一个用于在Windows上操作串行端口的简单类。
我需要检查输入缓冲区是否为空。
到目前为止,我已经尝试通过EV_RXCHAR选项使用SetCommEvent,但是此方法无效。该功能似乎正在等待新字符的到来。如果我尝试发送char,睡眠一秒钟并应用它,该函数将不会返回-它一直在等待。
bool isEmpty()
{
DWORD dwEventMask = 0;
DWORD Status = 0;
if (CheckAsyncRead())
return false;
if (!SetCommMask(hPort, EV_RXCHAR)) //wait for char receival
std::cout << "Error in creating Overlapped event" << std::endl;
osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (WaitCommEvent(hPort, &dwEventMask, &osReader))
{
//close event handle
return false;
}
Status = WaitForSingleObject(osReader.hEvent, 10);
//I wait for 10 ms in case the function doesn't return immediately
//Close event handle
if (Status == WAIT_OBJECT_0)
{
return false;
}
else
return true;
}
我希望在缓冲区中存在任何字符的情况下,WaitCommEvent或WaitForSingleObject会返回,但是如果在接收字符和调用Wait函数之间存在更长的停顿,那不会发生。
答案 0 :(得分:0)
您可以将ReadFile()与带有FILE_FLAG_OVERLAPPED标志的CreateFile()打开的句柄一起使用。如果ReadFile()函数没有任何要返回的内容,它将返回最后一个错误ERROR_IO_PENDING,这意味着您的缓冲区当前为空。
答案 1 :(得分:0)
您可以使用ClearCommError function来找出缓冲区中存储的数据大小。
作为调用的结果,要通知的COMSTAT structure的cbInQue具有存储在输入缓冲区中的数据大小。