使用Boost过程获取Shell命令的标准输出

时间:2018-09-25 10:54:29

标签: c++ boost boost-process

我正在尝试在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网站上的example中,在while循环中检查了条件c.running()。如果进程在到达while循环之前完成执行该怎么办?在这种情况下,我将无法将子进程的标准输出存储到数据中。 Boost的documentation还提到了以下

  

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

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

如何在程序到达while循环之前从完成运行的进程中获取stdout(和stderr)?

1 个答案:

答案 0 :(得分:0)

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

相关问题