我用CreateFile以FILE_FLAG_OVERLAPPED形式打开了一个串口设备进行异步通信,在使用ReadFile时
传入的Overlapped结构体与事件都是正确初始化的,但是在使用WaitForMultipleObjects等待两个事件时,WaitForMultipleObjects总是返
回overlapped结构体里面的事件, 虽然看起来是等待成功了,我紧接
着再调用GetOverlappedResult,但显示已传送的字节数却为0, 请问这是为什么? WaitForMultipleObjects
为什么不能等待(或是说失败)了? 这个问题真够纠结的,不知道要同步的话,怎么弄才好.
OVERLAPPED overlap = {0};
overlap.hEvent = hReadEvent;
debug_out(("进入ReadFile\n"));
retval = ReadFile(msg.hComPort, &block_data[0]+nTotalRead, nBytesToRead-nTotalRead, NULL, &overlap);
if(retval == TRUE){//-------------------------------------------------一次性把所有的数据读完了
retval = GetOverlappedResult(msg.hComPort,&overlap,&nRead,FALSE);
if(retval == FALSE){
debug_out(("GetOverlappedResult返回FALSE错误, 线程退出!\n"));
utils.msgerr("GetOverlappedResult");
goto __exit;
}else{
nTotalRead += nRead;
debug_out(("读线程中的ReadFile返回了TRUE!\n"));
}
}else{//--------------------------------------------------------------- IO被Pending了
HANDLE hWaitEvents[2];
DWORD err = GetLastError();
if(err != ERROR_IO_PENDING){
debug_out(("ReadFile()==FALSE&&GetLastError()!=ERROR_IO_PENGING\n"));
utils.msgerr("GetLastError()!=ERROR_IO_PENDING");
goto __exit;
}
hWaitEvents[0] = deal.thread.hEventRead;
hWaitEvents[1] = hReadEvent;
//这是总是马上就结束了,尽管ReadFile没有完成~
err=WaitForMultipleObjects(2,hWaitEvents,FALSE,/*flag==0?INFINITE:*/3000);
debug_out(("等待2结束:err=%d\n",err));
//debug_out(("退出等待~\n"));
switch(err)
{
case WAIT_OBJECT_0+0://关闭,取消读取
debug_out(("因为WAIT_OBJECT_0+0,读线程退出!\n"));
goto __exit;
case WAIT_OBJECT_0+1:
//debug_out(("读线程等待已结束,已读取到数据!\n"));
break;
case WAIT_FAILED:
debug_out(("读操作线程中的等待函数返回WAIT_FAILED!\n"));
utils.msgerr("WaitForMultipleObjects");
goto __exit;
case WAIT_TIMEOUT:
{
debug_out(("在等待最后一个中文字符时,等待超时!\n"));
block_data[nBytesToRead-1] = '?';//不正确的最后一个字节
goto _continue;
}
}
//debug_out(("进入GetOverlappedResult!\n"));
retval = GetOverlappedResult(msg.hComPort,&overlap,&nRead,FALSE);
if(retval == FALSE){
debug_out(("GetOverlappedResult返回FALSE错误, 线程退出!\n"));
utils.msgerr("GetOverlappedResult");
goto __exit;
}
//debug_out(("GetOverlappedResult:返回了 %d 字节!\n",nRead));
nTotalRead += nRead;
}
[招生]科锐逆向工程师培训(2024年11月15日实地,远程教学同时开班, 第51期)