简体   繁体   English

在多线程c ++中捕获进程的输出

[英]Capture the output of a process in multi-threaded c++

My requirements are simple: start a process, wait for it to finish, then capture and process it's output. 我的要求很简单:启动一个进程,等待它完成,然后捕获并处理它的输出。

For the longest time I've been using the following: 我使用以下内容的时间最长:

struct line : public std∷string {
    friend std∷istream& operator>> (std∷istream &is, line &l) {
        return std∷getline(is, l);
    }
};

void capture(std::vector<std::string> &output, const char *command)
{
    output.clear();
    FILE *f = popen(command, "r");
    if(f) {
        __gnu_cxx::stdio_filebuf<char> fb(f, ios∷in) ;
        std::istream fs(&fb);
        std::istream_iterator<line> start(fs), end;
        output.insert(output.end(), start, end);
        pclose(f);
    }
}

And it works really well on single threaded programs. 它在单线程程序上运行得非常好。

However, if I call this function from inside a thread, sometimes the popen() call hangs and never return. 但是,如果我从一个线程内部调用此函数,有时popen()调用会挂起并且永远不会返回。

So, as a proof-of-concept I replaced the function for this ugly hack: 因此,作为一个概念验证,我替换了这个丑陋黑客的功能:

void capture(std::vector<std::string> &output, const char *command)
{
    output.clear();
    std::string c = std::string(command) + " > /tmp/out.txt";
    ::system(c.c_str());
    ifstream fs("/tmp/out.txt", std::ios::in);
    output.insert(output.end(), istream_iterator<line>(fs), istream_iterator<line>());
    unlink("/tmp/out.txt");
}

It's ugly but works, however it kept me wondering what would be the proper way to capture a process output on a multi-threaded program. 这很丑陋但有效,但它让我想知道在多线程程序上捕获进程输出的正确方法是什么。

The program runs on linux in a embedded powerquiccII processor. 该程序在嵌入式powerquiccII处理器的linux上运行。

See this: popen - locks or not thread safe? 看到这个: popen - 锁或不是线程安全吗? and other references do not seem conclusive that popen() needs to be thread-safe, so perhaps since you are using a less-popular platform, your implementation is not. 和其他引用似乎并不确定popen()需要是线程安全的,所以也许因为你使用的是一个不太受欢迎的平台,你的实现不是。 Any chance you can view the source code of the implementation for your platform? 您是否有机会查看平台的实施源代码?

Otherwise, consider creating a new process and waiting upon it. 否则,请考虑创建一个新进程并等待它。 Or hey, stick with the silly system() hack, but do handle its return code! 或者嘿,坚持使用愚蠢的系统()hack,但要处理它的返回码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM