windows ReadFile() doesn't return until reading sizeToRead value

末鹿安然 提交于 2020-12-16 04:51:43

问题


In serial communication, ReadFile doesn't return until reading as many as sizeToRead parameter.

It is so weird, because actually until yesterday, it works normally with same code, same laptop, returning though it doesn't receive as many as sizeToRead but any bytes.

But today my code show weird symptom like this.

serialHandle = CreateFile(L"\\\\.\\COM1",
    GENERIC_READ | GENERIC_WRITE,
    0,
    0,
    OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL,
    0);

DCB serialInfo = {0};

GetCommState(serialHandle, &serialInfo)

serialInfo.DCBlength = sizeof(DCB);
serialInfo.BaudRate = CBR_19200;
serialInfo.fBinary = TRUE;
serialInfo.fParity = TRUE;          
serialInfo.fErrorChar = TRUE;
serialInfo.fNull = TRUE;
serialInfo.fAbortOnError = FALSE;   //TODO
serialInfo.ByteSize = 8;
serialInfo.Parity = SPACEPARITY;
serialInfo.StopBits = ONESTOPBIT;
serialInfo.ErrorChar = 0xFF;    

SetCommState(serialHandle, &serialInfo

ReadFile(serialHandle, buffer, numberOfBytesToRead, &numOfBytesRead, NULL)

numberOfBytesToRead is 256, So ReadFile return after getting 256 bytes


回答1:


ReadFile can return before reading numOfBytesRead based on a timeout, see SetCommTimeouts. If you have not initialized the timeout settings then you inherit whatever was set by other programs. So for consistent behavior 1you should call this API when you open the COM port.



来源:https://stackoverflow.com/questions/26947356/windows-readfile-doesnt-return-until-reading-sizetoread-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!