我的API串口通信程序,注意:接收正常,是重叠方式的,开了一个线程进行接收
m_osWrite已经过初始化,
memset(&m_osWrite,0,sizeof(OVERLAPPED));
m_osWrite.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);且初始化成功
但发送始终超时。
经调试,总是进入等待GetOverlappedResult(m_hCom,&m_osWrite,&length,TRUE)
请大家分析一下,是什么原因!
DWORD CCOMM::WriteComm(char * buf, DWORD dwLength) //发送
{
 BOOL fState;
 DWORD length=dwLength;
 COMSTAT ComStat;
 DWORD dwErrorFlags; ClearCommError(this->m_hCom,&dwErrorFlags,&ComStat);
 fState=WriteFile(this->m_hCom,buf,length,&length,&m_osWrite);
 if (!fState)
 {
  if(GetLastError()==ERROR_IO_PENDING)
  {
   GetOverlappedResult(m_hCom,&m_osWrite,&length,TRUE);
  }
  else
  {
    length=0;
   }
 }
return length;
}

解决方案 »

  1.   

    看到MSDN中有这样的注解:
    After the write operation has been completed, the file pointer is adjusted by the number of bytes actually written, except when the file is opened with FILE_FLAG_OVERLAPPED. If the file handle was created for overlapped input and output (I/O), the application must adjust the position of the file pointer after the write operation is finished.
    我在打开串口时是用
    CreateFile(sPort,GENERIC_READ | GENERIC_WRITE,
     0, NULL, OPEN_EXISTING,
    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,     //重叠
    NULL);
    语句打开串口的,那么我在写串口的时候如何调整文件指针呢?是否需要调整?
    我在监听线程中判断串口状态
    if (ComStat.cbOutQue)
      ******************
      PostMessage ******
      ******************
    if (ComStat.cbInQue)
      ******************
      PostMessage ******
      ******************
    这样写正确吗?
      

  2.   

    异步方式fState的值始终是0,很快就返回了,所以不能用返回值来判断,要用事件机制