使用ReadFile()时如何更改ReadFile的timeout
使用ReadFile()函数时,当在N秒内没有收到自己定义的数据包,则会timeout。那么N秒的具体时间如何定义?
用异步方式(OVERLAPPED)打开,即ReadFile()最后一个参数关联一个OVERLAPPED指针,然后用WaitForSingleObject去等待这个异步的句柄,即可实现。
WaitForSingleObject()函数的第二个参数,即可简单理解为timeout时间。
WaitForSingleObject的用法
DWORDWaitForSingleObject ( HANDLEhHandle, DWORDdwMilliseconds );
参数 hHandle是一个事件的句柄,第二个参数dwMilliseconds是时间间隔。如果时间是有信号状态返回 WAIT_OBJECT_0,如果时间超过 dwMilliseconds值但时间事件还是无信号状态则返回 WAIT_TIMEOUT 。
WaitForSingleObject函数用来检测hHandle事件的信号状态,当函数的执行时间超过dwMilliseconds就返回,但如果参数dwMilliseconds为INFINITE时函数将直到相应时间事件变成有信号状态才返回,否则就一直等待下去,直到WaitForSingleObject有返回直才执行后面的代码。
http://www.cnblogs.com/andyhere/archive/2008/10/20/1314803.html
程序实例:
<span style="font-size:14px;">/*API call:ReadFile "Returns: the report in InputReport. "Requires: a device handle returned by CreateFile "(for overlapped I/O, CreateFile must be called with FILE_FLAG_OVERLAPPED), "the Input report length in bytes returned by HidP_GetCaps, "and an overlapped structure whose hEvent member is set to an event object. */ if (ReadHandle != INVALID_HANDLE_VALUE) { Result = ReadFile (ReadHandle, InputReport, Capabilities.InputReportByteLength, &NumberOfBytesRead, (LPOVERLAPPED) &HIDOverlapped ); } // DisplayLastError("ReadFile: ") ; /*API call:WaitForSingleObject "Used with overlapped ReadFile. "Returns when ReadFile has received the requested amount of data or on timeout. "Requires an event object created with CreateEvent "and a timeout value in milliseconds. */ Result = WaitForSingleObject (hEventObject, 20000); // 这个时间就可以理解为timeout时间 switch (Result) { case WAIT_OBJECT_0: { // 接收到自定义数据包处理程序 break; } case WAIT_TIMEOUT: { // timeout处理程序 break; } } </span>
reference:http://bbs.eeworld.com.cn/thread-150077-1-1.html
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: C语言怎样提取一个数的十位个位百位千位
- 下一篇:没有了