移除 USB 设备时以编程方式中断串行 I/O - C++

发布于 2024-10-06 08:34:39 字数 175 浏览 0 评论 0原文

我有一个应用程序,其中串行 I/O 是通过虚拟 COM 端口使用连接的 USB 设备进行的。当检测到设备意外移除时,停止串行 I/O 的最佳方法是什么。我应该简单地关闭端口吗?或者,是否应该有一个全局变量来维护以指示设备的存在,并在尝试传输/接收数据之前在每个串行 I/O 函数中检查该变量?或者,应该是两者的结合,还是其他什么?谢谢。

I have an application wherein serial I/O is conducted with an attached USB device via a virtual COM port. When surprise removal of the device is detected, what would be the best way to stop the serial I/O. Should I simply close the port? Or, should there be a global variable, which is maintained to indicate the presence of the device, that should be checked in each serial I/O function prior to attempting to transmit/receive data? Or, should it be a combination of the two, or something else? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自控 2024-10-13 08:34:39

我假设您运行的是 Windows。
这取决于您如何设计通信流程。

我有一个 BasePort 对象,我在其中派生了一个 COMPort 对象(以及许多其他通信对象)。 COMPort 对象创建一个 TXThread 和 RXThread 类。这些线程正在等待“OVERLAP”,以通过 WaitForMultipleObjects() 发出读取或写入操作完成的信号。

如果无事可做,TXThreads 将进入休眠状态,并由 TXWrite 函数唤醒(主进程和线程之间的数据通过 trhead 安全 FIFO 缓冲区)。

在这种情况下,他们还需要等待端口已关闭的事件信号,因此他们实际上可以取消任何挂起的操作并退出(线程退出并被删除)。

为了检测 USB 端口是否已连接/断开,我监听 Windows 消息 DEVICE_CHANGE。如果端口断开连接,我会设置事件并等待线程退出,然后再端口类删除并关闭端口。

我发现这种方法非常可靠和安全。它是我 8 年前设计的通信平台的核心,并且仍然有效。

I'm assuming you are running Windows.
This depends on how you have designed your communication flow.

I have a BasePort object where I have derived a COMPort object (and many other communication objects). The COMPort object creates one TXThread and RXThread class. These threads are waiting for the "OVERLAP" to signal that the read or write operation finished with WaitForMultipleObjects().

The TXThreads goes to sleep if there is nothing to do and wakes up by the TXWrite function (the data between main process and thread goes through a trhead safe FIFO buffer).

In this case they also need to wait for an event signal that the port has closed, so they actually can cancel any pending operations and exit (the treads exits and gets deleted).

To detect if the USB port is connectd/disconneted I listen for the Windows message DEVICE_CHANGE. If the port is disconnected I set the event and waits for the threads to exit before the Port class deletes and closes the port.

I have found this approach very reliable and safe. It's the core in a communication platform I designed for over 8 years ago and still kicking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文