简体   繁体   English

使用 Boost C++ 使用管道将输出从子进程发送到父进程(将标准输出重定向到管道)

[英]Sending output from child process to parent using pipe (redirecting stdout to pipe) using Boost C++

I am new to Boost library.我是 Boost 库的新手。 I am trying to spawn a child process using bp::child c() and redirecting the stdout to a pipe/stream.我正在尝试使用bp::child c()生成子进程并将标准输出重定向到管道/流。 The problem that I am facing is, converting that stream to a string requires the use of getline , which is blocking.我面临的问题是,将该流转换为字符串需要使用getline ,这是阻塞的。 As such, creating the child process and executing it is non-blocking, as mentioned in the documentation.因此,如文档中所述,创建子进程并执行它是非阻塞的。 But since getline is blocking, the code after getline has to wait until the child process has completed execution.但是由于 getline 是阻塞的,getline 之后的代码必须等到子进程完成执行。

Is there a non-blocking alternative to getline ?是否有非阻塞替代 getline ? Or should I be trying a different way to communicate the output of child process to parent ?或者我应该尝试以不同的方式将子进程的输出传达给父进程? Here is the sample code for reference :这是供参考的示例代码:

bp::ipstream p;
bp::child c(cmd, bp::std_out > p);
std::string line;
std::getline(p, line)
std::cout<<line;

//doSomething();

c.wait();

The answer is no.答案是不。 Boost also provided the asio library implementing asynchronous I/O. Boost 还提供了实现异步 I/O 的asio库。 You can try with it Here is an example for reference你可以试试看这里有一个例子供参考

boost::asio::io_service ios; 
std::vector<char> buf(4096);    
bp::async_pipe ap(ios);    
bp::child c(cmd, bp::std_out > boost::asio::buffer(buf), ios);
//Do something
ios.run();
std::string s(buf.begin(), buf.end());
std::cout << s;
c.wait();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM