简体   繁体   English

Windows ReadFile()直到读取sizeToRead值才返回

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

In serial communication, ReadFile doesn't return until reading as many as sizeToRead parameter. 在串行通信中, ReadFile直到读取多达sizeToRead参数才返回。

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. 太奇怪了,因为实际上直到昨天,它仍然可以使用相同的代码,相同的笔记本电脑正常工作,尽管返回的字节数sizeToRead但返回的字节数sizeToRead

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 numberOfBytesToRead为256,因此ReadFile在获得256个字节后返回

ReadFile can return before reading numOfBytesRead based on a timeout, see SetCommTimeouts. ReadFile可以在基于超时读取numOfBytesRead之前返回,请参见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. 因此,对于一致的行为1,打开COM端口时应调用此API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM