gpt4 book ai didi

winapi - Win32 API : ReadFile not timing out

转载 作者:行者123 更新时间:2023-12-05 01:16:05 26 4
gpt4 key购买 nike

我正在编写一些代码来连接硬件。硬件通过 USB 与设备内的 USB 转串口转换器连接到 PC(它在 Windows 中显示为 COM 端口设备)。

我在使用 Win32 API ReadFile 系统调用时遇到问题。我似乎无法让它像宣传的那样工作。我已经设置了 COMMTIMEOUTS 结构:

COMMTIMEOUTS ct;
ct.ReadIntervalTimeout = MAXDWORD;
ct.ReadTotalTimeoutconstant = 0;
ct.ReadTotalTimeoutMultiplier = 0;
ct.WriteTotalTimeoutConstant = 0;
ct.WriteTotalTimeoutMultiplier = 0;

if(SetCommTimeouts(device_id_, &ct) == 0)
{
return ERROR; // this is never hit.
}

根据 Win32 API 文档,它说:

ReadIntervalTimeout

The maximum time allowed to elapse between the arrival of two bytes on the communications line, in milliseconds. During a ReadFile operation, the time period begins when the first byte is received. If the interval between the arrival of any two bytes exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used.

A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the bytes that have already been received, even if no bytes have been received.

我发送的命令应该返回一个单字节整数。大多数情况下,设备会收到命令并返回适当的值。然而,有时它似乎不返回值并且 ReadFile() 阻塞直到收到更多字节(例如,通过按下设备上的按钮)。一旦按下按钮,就会收到我期望的初始整数响应以及按钮按下代码。根据 MSDN 文档,虽然这不是我所期望的设备本身的行为,但我更关心的是 ReadFile() 在不应该的情况下被阻塞。在这里阻塞 ReadFile() 是否有补救措施?

最佳答案

噢!原来 ReadFile 阻塞只是一个症状,而不是问题所在。有问题的硬件设备只有一个 4MHz 的处理器。拆分写入设备的 3 字符命令并在字符之间暂停 1 毫秒来单独发送它们可以解决此问题。

关于winapi - Win32 API : ReadFile not timing out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3982977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com