I have certain problem and I am not sure what I am doing wrong.
//sleeper.exe
int main()
{
int i = 0;
while (true)
{
printf("%i\n", ++i);
sleep_for(1s);
}
return 0;
}
I want to capture sleeper's output in my application and add it line by line to some container;
//application.exe
int main()
{
io_context context;
async_pipe out(context);
child sleeper("sleeper.exe", std_out > out, context);
vector<string> lines;
streambuf buffer;
async_read_until(out, buffer, '\n', [](const error_code& code, size_t size)
{
// Add line to container
});
context.run();
return 0;
}
Unfortunately my application hangs on context.run()
, probably because sleeper application never terminates. But it should read sleeper's output until delimiter, so I do not know what is the problem here. I am looking forward some explanation.
Edit after more research on topic:
According to: https://support.microsoft.com/en-us/help/190351/how-to-spawn-console-processes-with-redirected-standard-handles
Note Child processes that use such C run-time functions as printf() and fprintf() can behave poorly when redirected. The C run-time functions maintain separate IO buffers. When redirected, these buffers might not be flushed immediately after each IO call. As a result, the output to the redirection pipe of a printf() call or the input from a getch() call is not flushed immediately and delays, sometimes-infinite delays occur. This problem is avoided if the child process flushes the IO buffers after each call to a C run-time IO function. Only the child process can flush its C run-time IO buffers. A process can flush its C run-time IO buffers by calling the fflush() function.
I am still looking for solution in this field.