windows ReadFile() 在读取 sizeToRead 值之前不会返回 [英] windows ReadFile() doesn't return until reading sizeToRead value

查看:59
本文介绍了windows ReadFile() 在读取 sizeToRead 值之前不会返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在串行通信中,ReadFile 直到读取了 sizeToRead 参数后才返回.

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

这太奇怪了,因为实际上直到昨天,它仍然可以使用相同的代码、相同的笔记本电脑正常工作,虽然它没有接收到 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.

但今天我的代码显示出这样的奇怪症状.

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 是 256,所以 ReadFile 得到 256 字节后返回

numberOfBytesToRead is 256, So ReadFile return after getting 256 bytes

推荐答案

ReadFile 可以根据超时在读取 numOfBytesRead 之前返回,请参阅 SetCommTimeouts.如果您尚未初始化超时设置,那么您将继承其他程序设置的任何内容.因此,为了保持一致的行为 1,您应该在打开 COM 端口时调用此 API.

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.

这篇关于windows ReadFile() 在读取 sizeToRead 值之前不会返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆