有没有办法记录通过 boost::process::spawn 创建的进程的输出?

Is there a way to log the output of a process create via boost::process::spawn?

我知道有一种方法 boost::process::child 描述 here:

boost::asio::boost::asio::io_service ios;

std::future<std::string> data;
child c("g++", "main.cpp", //set the input
        bp::std_in.close(),
        bp::std_out > bp::null, //so it can be written without anything
        bp::std_err > data,
        ios);


ios.run(); //this will actually block until the compiler is finished

auto err =  data.get();

这可以在调用 boost::process::spawn 时工作吗?还是我必须使用 boost::process::child 才能这样做?

不,那是不可能的。它隐含在 documentation:

This function does not allow asynchronous operations, since it cannot wait for the end of the process. It will fail to compile if a reference to boost::asio::io_context is passed.

也许你可以用 child::detach 代替?

#include <boost/process.hpp>
#include <boost/asio.hpp>
#include <iostream>
namespace bp = boost::process;

int main()
{
    boost::asio::io_service ios;

    std::future<std::string> data;

    bp::child c("/usr/bin/g++", "main.cpp", // set the input
                bp::std_in.close(),
                bp::std_out > bp::null, // so it can be written without anything
                bp::std_err > data, ios);
    c.detach();

    ios.run(); // this will actually block until the compiler is finished

    auto err = data.get();
    std::cout << err;
}