c++boostboost-asioboost-process

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


I know that there is a way with a boost::process::child as described 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();

Can this work when calling boost::process::spawn or do I have to use a boost::process::child to do so?


Solution

  • No that is not possible. It's implied in the 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.

    Maybe you can use child::detach instead?

    #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;
    }