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

2023-12-27

我正在尝试在 C++ 中实现一个函数,该函数运行 shell 命令并返回退出代码,stdout and 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 https://www.boost.org/doc/libs/1_68_0/doc/html/boost_process/tutorial.html#boost_process.tutorial.io从 boost 的网站来看,在 while 循环中检查条件 c.running() 。如果进程在到达 while 循环之前完成执行怎么办?在这种情况下,我将无法将子进程的标准输出存储到数据中。升压的文档 https://www.boost.org/doc/libs/1_68_0/doc/html/boost_process/tutorial.html#boost_process.tutorial.io还提到以下内容

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

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

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


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 boost 进程获取 shell 命令的标准输出 的相关文章

随机推荐