Andrew Tomazos
Andrew Tomazos

Reputation: 68698

Getting exit code of boost::process::child under boost::asio::io_service?

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?

Upvotes: 2

Views: 2457

Answers (2)

Giovanni Cerretani
Giovanni Cerretani

Reputation: 1724

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.

Upvotes: 0

G.M.
G.M.

Reputation: 12899

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

Upvotes: 4

Related Questions