30

我正在尝试将 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或其他主循环。

4

1 回答 1

33

这正是null_buffers旨在解决的问题。

有时程序必须与想要自己执行 I/O 操作的第三方库集成。为了促进这一点,Boost.Asio 包含一个 null_buffers 类型,它可以用于读取和写入操作。在 I/O 对象“准备好”执行操作之前,null_buffers 操作不会返回。

例如,要执行非阻塞读取,可以使用以下内容:

ip::tcp::socket socket(my_io_service);
...
ip::tcp::socket::non_blocking nb(true);
socket.io_control(nb);
...
socket.async_read_some(null_buffers(), read_handler);
...
void read_handler(boost::system::error_code ec)
{
  if (!ec)
  {
    std::vector<char> buf(socket.available());
    socket.read_some(buffer(buf));
  }
}

文档中还包含一个很好的示例

于 2011-01-13T23:32:21.280 回答