我正在尝试将 D-Bus 与我的boost::asio
应用程序集成。
D-Bus 有一个 API 可以枚举一组 Unix 文件描述符(主要是套接字,但也可以是 FIFO)以进行监视。当这些描述符有要读取的内容时,我应该通知 D-Bus API,以便它可以读取它们并执行此操作。
目前我正在这样做:
using boost::asio::posix::stream_descriptor;
void read_handle(stream_descriptor* desc, const boost::system::error_code& ec,
std::size_t bytes_read)
{
if (!ec) {
stream_descriptor::bytes_readable command(true);
descriptor->io_control(command);
std::size_t bytes_readable = command.get();
std::cout << "It thinks I should read" << bytes_readable
<< " bytes" << std::endl;
} else {
std::cout << "There was an error" << std::endl;
}
}
void watch_descriptor(boost::asio::io_service& ios, int file_descriptor)
{
// Create the asio representation of the descriptor
stream_descriptor* desc = new stream_descriptor(ios);
desc->assign(file_descriptor);
// Try to read 0 bytes just to be informed that there is something to be read
std::vector<char> buffer(0);
desc->async_read_some(boost::asio::buffer(buffer, 0),
boost::bind(read_handle, desc, _1, _2));
}
但是处理程序被立即调用,说它有 0 个字节要读取。我希望仅在有要阅读的内容时才调用它,但是 boost::asio 无法读取它。它应该作为一个荣耀select()
。有没有一种简单的方法可以做到这一点?
PS:我boost::asio
在我的软件中广泛使用,这只是其中的一小部分,所以我不想依赖glib
或其他主循环。