boost :: process异步IO示例不起作用? [英] boost::process async IO example doesn't work?

查看:279
本文介绍了boost :: process异步IO示例不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序:

#include <boost/asio.hpp>
#include <boost/process.hpp>
#include <iostream>

namespace bp = boost::process;

int main() {
    boost::asio::io_service ios;
    std::vector<char> buf(4096);

    bp::async_pipe ap(ios);

    bp::child c("/bin/ls", bp::std_out > ap);

    boost::asio::async_read(ap, boost::asio::buffer(buf),
            [](const boost::system::error_code &ec, std::size_t size){});

    ios.run();
    int result = c.exit_code();
    std::cout << result << std::endl;
}

输出383.我希望它输出0.

这几乎是该示例的复制粘贴:

This is very nearly a copy-and-paste of the example from:

https://www.boost.org/doc/libs/1_71_0/doc/html/boost_process/tutorial.html#boost_process.tutorial.async_io

推荐答案

此处可能存在一些问题.首先,我认为

There may be a few issues here. Firstly, I think the comment in the documentation...

将boost :: asio :: io_service的实例传递给启动 函数会自动使其异步等待退出, 所以不需要等待

Passing an instance of boost::asio::io_service to the launching function automatically cause it to wait asynchronously for the exit, so no call of wait is needed

...在您显示的代码之后,请参见示例 .具体来说...

...refers to the example after the code you've shown. Specifically...

boost::asio::io_service ios;
std::vector<char> buf(4096);

bp::child c(bp::search_path("g++"), "main.cpp", bp::std_out > boost::asio::buffer(buf), ios);

ios.run();
int result = c.exit_code();

io_service通过引用传递给child ctor的地方.

Where the io_service is passed by reference to the child ctor.

此评论也有些误导.的确,随后对ios.run() 的调用确实异步等待退出,但同时也出现了(提升1.71.0)退出代码未如人们所希望的那样被固定.退出代码存储为child类中的...

The comment is also slightly misleading. While it's true that the subsequent call to ios.run() does wait asynchronously for the exit it also appears (boost 1.71.0) that the exit code is not fixed up as one might hope. The exit code is stored within the child class as...

std::shared_ptr<std::atomic<int>> _exit_status;

从源代码的快速扫描看来,似乎仅从以下成员调用了_exit_status->store(...) ...

From a quick scan of the source code it seems _exit_status->store(...) is only invoked from the following members...

boost::process::child::running
boost::process::child::wait
boost::process::child::wait_until

因此,即使ios.run()返回running中的一个或多个时,进程已经退出(假设一切顺利),也必须调用waitwait_until才能使退出代码可用.

So, even though the process has exited (assuming all went well) when ios.run() returns one or more of running, wait or wait_until must be called to make the exit code available.

正如@sehe在其他地方评论的那样,这似乎是一种回归.如果我可以找到错误报告,则将对其进行更新.同时,解决方法是在c.exit_code()之前简单地调用c.wait().

As commented elsewhere by @sehe this looks like it's possibly a regression. If I can find a bug report I'll update this. In the meantime the workaround is to simply call c.wait() before c.exit_code().

这篇关于boost :: process异步IO示例不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆