Is wait() needed after run() in boost process async child process?

2.1k Views Asked by At

I am using Boost Process in async mode to get the stdout, stderr and return code of a shell command. In the code snippet below, is the call c.wait() required? According to Boost Process 1.68 documentation it is not required where as it is required according to that of boost process 1.65.1.

std::string command = "ls";
boost::asio::io_service ios;
std::future<std::string> dataOut;
std::future<std::string> dataErr;
bp::child c(command, bp::std_in.close(), bp::std_out > dataOut, bp::std_err > dataErr, ios);
ios.run();
c.wait();
stdOut = dataOut.get();
stdErr = dataErr.get();
returnStatus = c.exit_code();

Now, I am using Boost 1.68 and when I remove the call to c.wait(), I get a returnStatus of 127 instead of the expected 0, which I get when I add the c.wait() call. What difference does the call c.wait() make?

2

There are 2 best solutions below

0
On

.wait will wait for signal from the child process and if already signaled meanning already finish the run, will assignee the correct exit code returned from the CMD, without waiting u will get 127 as you noticed.

Wait function from boost

1
On

Yes, run() normally waits for async operations to complete.

However, you could have an alternative termination of run()

  • when an exception emanates from a handler
  • when another thread calls stop()
  • when async signals alter program flow

In such cases it would be advisable to still use wait() so you avoid zombies. Other than that, the on_exit() handler is the more flexible approach, in that it will allow you to multiplex several processes on the same io_context/io_service instance and still respond to child process completion as soon as possible.