使用提升过程获取 shell 命令的标准输出

Get stdout of a shell command using boost process

本文关键字:shell 命令 标准输出 获取 过程      更新时间:2023-10-16

我正在尝试在C++中实现一个函数,该函数运行 shell 命令并返回退出代码,stdoutstderr.我正在使用Boost process library

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;
}

在上面来自boost网站的例子中,在while循环中检查了条件c.running((。如果进程在到达 while 循环之前完成执行怎么办?在这种情况下,我将无法将子进程的标准输出存储到数据中。Boost的文档还提到了以下内容

[警告] 警告 如果在 nm 退出后尝试读取,管道将导致死锁

因此,似乎对 c.running(( 的检查应该在 while 循环中存在。

如何从程序到达 while 循环之前完成运行的进程获取标准输出(和标准输出(?

我相信等待电话是为了什么。在此之前的任何操作系统中,子进程实际上并没有消失(它只是在不处于运行状态后更改状态(。