各位大侠:小弟程序是用来USB通讯的,同步(已经不能改异步了),因为通讯时USB设备断开会令readfile阻塞,因此想要引入超时处理,SetCommTimeouts。问题是,SetCommTimeouts函数总是返回fail,GetLastError得到87(参数不正确),两个参数一个是通讯设备句柄,一个是超时设定,不知道哪里出错呀??
COMMTIMEOUTS   timeOver;   ……timeOver.ReadIntervalTimeout = 1000;
timeOver.ReadTotalTimeoutMultiplier = 1000;   
timeOver.ReadTotalTimeoutConstant = 1000;   
timeOver.WriteTotalTimeoutMultiplier = 1000;
timeOver.WriteTotalTimeoutConstant = 1000;
ret =  SetCommTimeouts(hRead,(LPCOMMTIMEOUTS)&timeOver);
if(ret == 0)
{
res = GetLastError();
strResult.Format("Err:%d \n",res);
MessageBox(strResult,   "Error",   MB_OK   |   MB_ICONINFORMATION   );   
//这里实际输出的是“Err:87“,也就是参数不正确。   
break;
}success = ReadFile(hRead,txBlk,txBlkSize,&respLen,NULL);
//由于种种原因,不能改为异步通讯
求教高人!!~~

解决方案 »

  1.   

    就两个参数,看看hRead是否有效吧。
      

  2.   

    谢谢1楼,我也怀疑过hRead是否有效,可是后面的ReadFile(hRead, ...)是正常的,是不是可以认为hRead有效?如何判定hRead是否有效呢?
      

  3.   

    同意1楼大哥,在 SetCommTimeouts 前要确保使用 CreateFile 成功打开设备。
      

  4.   

    谢谢3楼,hRead 在 readFile 中成功调用,实际运行读文件也成功,是否证明 hRead 句柄可用?
      

  5.   

    ReadFile正常,说明hRead正确打开了;但是我没用过USB模拟的COM,不知道其是否支持这个延时的设置,因为这些函数最终是调用驱动程序和设备进行通讯的,也许该设备不支持某项功能也会出现你说的错误。
      

  6.   

    调试了半天,没出路,刚试了GetCommTimeouts 函数,调用结果也是一样,87,看来hfile真的有问题?
      

  7.   

    GetCommTimeouts and SetCommTimeouts are specific to the serial port driver.
    They're not general-purpose functions which can be applied to any driver.You can probably get the effect you want by using overlapped I/O and then
    doing a WaitForSingleObject on the event object within the OVERLAPPED
    structure. WaitForSingleObject takes a millisecond timeout value.