【问题标题】:Using boost::asio::async_read failing but boost::asio::read works (am using io_stream.run_one())使用 boost::asio::async_read 失败但 boost::asio::read 有效(正在使用 io_stream.run_one())
【发布时间】:2012-01-16 12:46:36
【问题描述】:

我有一个本地 posix 套接字,我正在尝试使用 boost::asio::async_read 异步读取它。但是,当我这样做时:

// io_stream and fd are passed by reference to this function
asio::posix::stream_descriptor stream(io_stream);
stream.assign(fd);

boost::system::error_code ec;

asio::async_read(stream, buffer,
                 asio::transfer_at_least(1),
                 boost::bind(doRead,
                             asio::placeholders::error,
                             asio::placeholders::bytes_transferred));
size_t count = io_service.run_one(ec);

count 变量设置为 0,doRead 处理程序永远不会被调用,并且 ec 不包含错误。但是,如果我将异步读取替换为同步读取:

size_t count = asio::read(stream, buffer,
                          asio::transfer_at_least(1));

这行得通,我在 count 变量中得到了预期的数据量。

我的测试用例使用由“int pipe(int pipefd[2]);”创建的 fd并通过 asio::async_read 正常工作,因此我认为这可能是几个选项:

  • 我传递的本机描述符在某些方面与 async_read 不兼容,因此它会静默失败。我曾尝试通过打开和关闭阻止来创建它,但无济于事。
  • io_service 和 posix::stream_descriptor 是一些未连接的,因此 io_service 永远不会尝试运行读取。这可能是因为我通过引用传递了 io_service 吗? (就此而言,也在几个线程内?)

【问题讨论】:

  • A stream_descriptor 与来自pipe 的读取端的描述符一起工作得很好,请参阅this 答案。我怀疑你的第二颗子弹是你看到的行为的原因。请编辑您的问题并附上short, self contained, correct example 供我们分析。
  • 我会在星期一上班,因为我家里没有代码,谢谢!

标签: c++ boost boost-asio


【解决方案1】:

我发现了问题。

我在所属对象的初始化函数中调用了 io_service.stop(),因为它可以重新初始化。但是,在调用 stop 之后我没有调用 io_service.reset(),并且 io_service 在 stop 之后不会运行,直到调用 reset 为止。

RTFM 中的一课作为 stop 和 reset 记录了这一点。

但是 boost::system::error_code 变量并没有反映这种状态,这有点令人沮丧,因为它可以让我免于胡闹。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2013-02-24
    相关资源
    最近更新 更多