I am trying to implement reading and writing in the child process from/to the same pipe. Instead of pipe I'm using boost::process::pstream
and redirecting stdin
and stdout
in child process to that stream.
Simple example. I send a message from the main process to the child one, read it from the child process, and send it back to the main. The problem is that I'm receiving a garbage(empty string) in the main process back from the child process. What am I doing wrong?
The code example below works correct if I use separate streams for the input/output of the child process...
int main(int argc, char **argv) {
if (argc == 1)
{
bp::pstream p;
p << "What?" << endl;
bp::child c(argv[0], "OPTIONAL", bp::std_in=p,
bp::std_out=p, bp::std_err=stderr);
c.wait();
string x;
getline(p, x);
cout << "Received from child process:" << x << endl;
system("pause");
}
else {
string x;
getline(cin, x);
cerr << "Received from main process:" << x << endl;
cout << x << endl;
}
}
The output is following:
Received from main process:What?
Received from child process:
Press any key to continue . . .