Boost.process allows the usage of Boost.asio in order to perform asynchronous read.
From what I understand, this is useful to read output while process is running without having to wait for the process to terminate.
But to access this output, is it necessary to wait for the process to terminate, or is it possible to access it while process is running, and how?
Actually my need is to access the beginning of a process output (to check that it started as expected) while while keeping it running.
To detail the context, I run a process which I want to keep until the end of the execution:
boost::asio::io_service ios;
std::vector<char> buf;
bp::child c("process_that_needs_to_keep_running", args,
bp::std_out > boost::asio::buffer(buf), ios);
ios.run();
// I DON'T WANT WAIT FOR c TO TERMINATE
// but I want to check that buf contains some text that ensures me it started correctly
// the issue I have here is that I don't know how to read from buf, since its size and content might not be consistent
// is it possible to take a snapshot for instance?
check_started_correctly(buf);
Here the issue is that the producer creates output which I don't control, I just issues output.
CodePudding user response:
If you use bp::std_out > some_kind_of_buffer_or_future
you will usually get the result only at exit.
However, you can use an async_pipe
:
bp::async_pipe pipe(io);
bp::child c( //
"/bin/bash",
std::vector<std::string>{
"-c",
"for a in {1..20}; do sleep 1; echo message $a; done",
}, //
bp::std_out > pipe, //
bp::on_exit(on_exit), //
io);
Now, you have to explicitly do the IO on that pipe:
boost::asio::streambuf sb;
async_read_until( //
pipe, sb, "message 5\n", //
[&](error_code ec, size_t) { //
std::cout << "Got message 5 (" << ec.message() << ")" << std::endl;
});
This works: