【问题标题】:Capture the output of a process in multi-threaded c++在多线程 C++ 中捕获进程的输出
【发布时间】:2013-02-27 11:22:36
【问题描述】:

我的要求很简单:启动一个进程,等待它完成,然后捕获并处理它的输出。

我一直在使用以下内容的最长时间:

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

它在单线程程序上运行得非常好。

但是,如果我从线程内部调用此函数,有时popen() 调用会挂起并且永远不会返回。

因此,作为概念验证,我替换了这个丑陋的 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");
}

它很丑但是很有效,但是它让我想知道在多线程程序上捕获进程输出的正确方法是什么。

程序在嵌入式 powerquiccII 处理器的 linux 上运行。

【问题讨论】:

    标签: c++ linux posix capture


    【解决方案1】:

    看到这个:popen - locks or not thread safe? 和其他参考似乎并不能确定 popen() 需要是线程安全的,所以也许因为您使用的是不太受欢迎的平台,所以您的实现不是。您是否有机会查看您平台的实现源代码?

    否则,请考虑创建一个新进程并等待它。或者,嘿,坚持愚蠢的 system() hack,但要处理它的返回码!

    【讨论】:

    • 我得到的libc是预编译的二进制文件,没有源码。
    • 那么我认为如果你的目标是一个更“纯粹”的解决方案,你应该分叉一个进程(无论如何 popen 都会这样做,所以我们不是在谈论数量级的更多开销) ,并从那里调用popen。或者不用popen:stackoverflow.com/a/6744256/4323
    • 好的,我会尝试“纯”的方法。谢谢
    • 或手动执行pipeforkdup2execvepopen 完成的系统调用
    • 哎呀,就此而言,也许您可​​以找到一个获得适当许可的开源 popen() 实现,它是线程安全的,只需使用它即可。
    猜你喜欢
    • 2011-05-18
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多