c++ - 使用 boost 进程获取 shell 命令的标准输出

标签 c++ boost boost-process

我正在尝试在 C++ 中实现一个函数,该函数运行 shell 命令并返回退出代码、stdoutstderr。 我正在使用 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/

相关文章:

c++ - 分析 SIMD 代码

c++ - COM、COM+、DCOM,从哪里开始?

C++ Boost 循环遍历未知的 ptree 和属性的列表值

C++:将映射文件读入矩阵的快速方法

c++ - 从 boost::process 到 boost::child 的信号传播

c++ - SQLite3 多进程性能测试

c++ - 在 Windows 8 上显示虚拟键盘

c++ - boost 中的单元测试

c++ - boost::process::child 会抛出什么异常?

c++ - 使用 boost 创建具有自定义环境的子进程