WaitCommEvent()是否报告已收到的数据?

时间:2012-11-08 20:28:13

标签: c++ winapi serial-port

我有一个程序在串行端口上执行重叠的I / O,我看到的情况是应用程序没有读取已接收的数据。我的代码使用SetCommMask()WaitCommEvent(),如下所示:

if(!waiting_for_comm_event)
{
   comm_event_ready = false;
   if(!SetCommMask(port_handle, EV_RXCHAR | EV_ERR | EV_RLSD))
      throw OsException(my_strings[strid_set_comm_mask_failed].c_str());
   rcd = WaitCommEvent(port_handle, &event_mask, &event_control);
   last_error = GetLastError();
   if(rcd && event_mask != 0)
       comm_event_ready = true;
   else if(last_error != ERROR_IO_PENDING)
       throw OsException(my_strings[strid_wait_comm_event_failed].c_str());
   else
       waiting_for_comm_event = true;
  }

在输出缓冲区中写入任何数据后调用此代码。在写这篇文章的过程中,有可能收到数据。 WaitCommEvent()会报告已经有数据等待读取的情况吗?

1 个答案:

答案 0 :(得分:3)

如果你在这里问,你不想知道答案。

不,真的 - 这意味着你依赖的是未来的Windows版本可能会改变的无证行为。

在发送触发数据和事件的数据之前,您可以使用重叠I / O来开始跟踪传入的数据和事件。

两种方法(我在自己的序列代码中使用第一种ReadFileEx变体):

  • 发出背景(重叠)阅读。
  • 发出背景(重叠)WaitCommEvent
  • 写下数据。
  • 等待两个后台操作...任何一个操作都将导致WaitForMultipleEvents继续进行。

  • 发出背景(重叠)WaitCommEvent
  • 写下数据。
  • 等待后台操作。
  • 如果唤醒事件是收到数据,请阅读。

在任何一种情况下,即使在WriteFile完成之前,也会检测到传入的数据和错误。