代码之家  ›  专栏  ›  技术社区  ›  bisarch

使用boost进程从shell命令中获取stdout

  •  3
  • bisarch  · 技术社区  · 7 年前

    我试图在C++中实现一个运行shell命令并返回退出代码的函数, stdout stderr. 我正在使用 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;
    }
    

    在上面 example 从Boost的网站,在while循环中检查条件c.running()。如果进程在到达while循环之前完成执行,该怎么办?在这种情况下,我将无法将子进程的stdout存储到数据中。增压器 documentation 还提到以下内容

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

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   darune    7 年前

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