我正在尝试在子进程中实现从/到同一管道的读取和写入。而不是管道,我正在使用并将子进程boost::process::pstream
重定向到该流。stdin
stdout
简单的例子。我从主进程向子进程发送一条消息,从子进程中读取它,然后将其发送回主进程。问题是我在主进程中从子进程接收到一个垃圾(空字符串)。我究竟做错了什么?
如果我对子进程的输入/输出使用单独的流,则下面的代码示例可以正常工作...
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;
}
}
输出如下:
Received from main process:What?
Received from child process:
Press any key to continue . . .