如何确保我们从boost :: child进程读取所有行 [英] How to ensure that we read all lines from boost::child process
问题描述
我在boost::child
文档页面上看到了以下代码,其中解释了如何读取子进程的输出.
http://www.boost.org/doc/libs/1_64_0/doc/html/boost_process/tutorial.html
他们说在运行您的子进程后,我们可以通过以下循环读取它:-
I saw the following code on boost::child
documentation page where they explain how to read the output of a child process.
http://www.boost.org/doc/libs/1_64_0/doc/html/boost_process/tutorial.html
They say after running your child process, we can read it via this loop:-
bp::ipstream is; //reading pipe-stream
bp::child c(bp::search_patk("nm"), file, bp::std_out > is);
//then later
while (c.running() && std::getline(is, line) && !line.empty())
data.push_back(line);
我在这里有2个问题:-
I have 2 questions here :-
- 如果
c.running()
返回false,我们仅退出循环.在那种情况下,上面的流is
可能仍会携带丢失的数据? - 在确保进程exit()不会造成死锁的同时读取stdout和stderr的最佳方法是什么
页面上显示警告:-
如果您在nm退出后尝试读取该管道,则会导致死锁
- If
c.running()
returns false, we simply exit the loop. And in that case, the streamis
above may still carry data which gets lost ? - What is the best way to read stdout and stderr both, while making sure the process exit() doesn't create a deadlock
There is a warning on the page saying :-
The pipe will cause a deadlock if you try to read after nm exited
我希望同时捕获stdout
和stderr
,而不必担心nm
已经退出还是不在上面.
I wish to capture both stdout
and stderr
without having to worry about nm
has exited or not above.
推荐答案
我认为除非您使用异步方法,否则没有正确的方法.
I think there's no proper way unless you use asynchronous methods.
也许您可以简单地将向量变成一个未来,并且如果确实需要逐行使用string_views,就可以使用它.
Perhaps you can simple get a future to a vector and use string_views into that if you somehow really need it line-by-line.
std::future<std::vector<char> > output, error;
boost::asio::io_service svc;
bp::child c(bp::search_path("nm"), file, bp::std_out > output, bp::std_err > error, svc);
svc.run();
要像在使用矢量流顶部之前使用istream之前一样完全阅读:
To read exactly like you did before you can use an istream on top of the vector:
#include <boost/process.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <iostream>
namespace bp = boost::process;
namespace bio = boost::iostreams;
std::string const file = "./a.out";
int main() {
std::future<std::vector<char> > output, error;
boost::asio::io_service svc;
bp::child c(bp::search_path("nm"), file, bp::std_out > output, bp::std_err > error, svc);
svc.run();
//then later
{
auto raw = output.get();
std::vector<std::string> data;
std::string line;
bio::stream_buffer<bio::array_source> sb(raw.data(), raw.size());
std::istream is(&sb);
while (std::getline(is, line) && !line.empty())
data.push_back(line);
std::cout << data.at(rand()%data.size()) << "\n";
}
}
这篇关于如何确保我们从boost :: child进程读取所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!