Get stdout of a shell command using boost process

有些话、适合烂在心里 提交于 2019-12-10 21:58:29

问题


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;
}

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

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

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

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


回答1:


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).



来源:https://stackoverflow.com/questions/52496487/get-stdout-of-a-shell-command-using-boost-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!