【发布时间】: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