我正在尝试在 C++ 中实现一个函数,该函数运行 shell 命令并返回退出代码、stdout
和 stderr。
我正在使用 Boost 进程图书馆
std::vector<std::string> read_outline(std::string & file)
{
bp::ipstream is; //reading pipe-stream
bp::child c(bp::search_path("nm"), file, bp::std_out > is);
std::vector<std::string> data;
std::string line;
while (c.running() && std::getline(is, line) && !line.empty())
data.push_back(line);
c.wait();
return data;
}
在上面example来自 boost 的网站,在 while 循环中检查条件 c.running() 。如果进程在到达 while 循环之前完成执行怎么办?在那种情况下,我将无法将子进程的标准输出存储到数据中。 boost 的 documentation还提到了以下内容
[Warning] Warning The pipe will cause a deadlock if you try to read after nm exited
因此,似乎应该在 while 循环中检查 c.running()。
如何从程序到达 while 循环之前完成运行的进程中获取标准输出(和标准错误)?
最佳答案
我相信等待调用是为了什么。在此之前,子进程实际上并没有在任何操作系统中消失(它只是在不处于运行状态后改变状态)。
关于c++ - 使用 boost 进程获取 shell 命令的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496487/