2

The following program:

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

int main() {
    boost::asio::io_service ios;
    boost::process::child c("/bin/ls");
    ios.run();
    std::cout << c.exit_code() << std::endl;
}

outputs 383:

$ g++ test.cc
$ ./a.out
383

I would expect it to output 0, as /bin/ls completes successfully.

What am I missing?

Andrew Tomazos
  • 66,139
  • 40
  • 186
  • 319

2 Answers2

4

You need to wait for child process to finish. From the documentation for boost::process::child::exit_code

The return value is without any meaning if the child wasn't waited for or if it was terminated.

So I would expect the following to give the expected result...

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

int main ()
{
    boost::process::child c("/bin/ls");
    c.wait();
    std::cout << c.exit_code() << std::endl;
}
G.M.
  • 12,232
  • 2
  • 15
  • 18
  • 1
    But in the boost::process tutorial: https://www.boost.org/doc/libs/1_71_0/doc/html/boost_process/tutorial.html#boost_process.tutorial.async_io It says `ios.run()` will block until child is finished. – Andrew Tomazos Dec 03 '19 at 12:14
  • 1
    Yes, but that example uses the io_service and an async_pipe to capture the process standard output. The code you have, however, doesn't make any use of the io_service in the sense that `ios.run()` has no operations to wait on and will, therefore, return immediately. Unless I'm misunderstanding something. – G.M. Dec 03 '19 at 12:19
  • Ok then, see this question: https://stackoverflow.com/questions/59157240/boostprocess-async-io-example-doesnt-work I observe the same problem with the example from boost process tutorial. – Andrew Tomazos Dec 03 '19 at 12:34
  • @G.M. Indeed io_service must be passed as a parameter for `run()` to imply the command completed – sehe Dec 03 '19 at 18:01
0

As a simple alternative, you can use boost::process::on_exit with a std::future<int>:

boost::asio::io_service ios;
std::future<int> exit_code;
boost::process::child c("/bin/ls", ios, boost::process::on_exit=exit_code);
ios.run();
std::cout << exit_code.get() << std::endl;

The call to std::future<T>::get will unlock as soon as the future has a value.

Giovanni Cerretani
  • 1,693
  • 1
  • 16
  • 30