【发布时间】:2022-12-18 14:29:02
【问题描述】:
我正在使用用于串行通信的 boost::asio 库,但在使用它时遇到了一些问题。下面是我的问题代码。
std::unique_ptr<asio::serial_port> port_;
asio::io_service io_;
// Connect serial port 'COM8'
port_ = std::make_unique<asio::serial_port>(asio::serial_port(io_, "COM8"));
std::cout << port_->is_open() << std::endl; // True
Sleep(5000);
/// **Now I unplug the device connected to the COM8 port of my PC.**
std::cout << port_->is_open() << std::endl;
/// Still printed true.
/// I think the reason @asio::serial_port::is_open() returns true
/// is because I didn't called @asio::serial_port::close() before.
/// Then how can I check the physical disconnection?
拔下设备后,如何以编程方式知道设备是否仍然可用?
【问题讨论】:
-
is_open()如果类实例是“开放的”。基本上,如果允许调用实例上的操作。也许有一些方法可以使用本机句柄来检测通信丢失,但它不可移植。通常在创建套接字后,会分配读/写例程,当该例程失败时,我们会得到指示,表明套接字出现问题。 -
串口通信没有检测连接/断开的方法,因为在协议级别没有定期的心跳或保持活动消息。你必须自己实施。
标签: c++ boost-asio