使用Boost过程获取Shell命令的标准输出 [英] Get stdout of a shell command using boost process

查看:623
本文介绍了使用Boost过程获取Shell命令的标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to implement a function in C++ that runs a shell command and returns the exit code, stdout and stderr. I am using the 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的文档还提到了以下

In the above example from boost's website, in the while loop the condition c.running() is checked. What if the process finishes executing before the while loop is reached? In that case I won't be able to store the child process's stdout to data. Boost's documentation also mentions the following

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

[Warning] Warning The pipe will cause a deadlock if you try to read after nm exited

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

Hence it seems that the check for c.running() should be there in the while loop.

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

How do I get the stdout (and stderr) from the processes that finish running before the program reaches the while loop?

推荐答案

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

I believe that whats the wait call is there for. The child process isn't actually gone in whatever OS before that (it merely changes state after it's not in running state).

这篇关于使用Boost过程获取Shell命令的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆