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

标签 c++ linux posix capture

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

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

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 上运行。

最佳答案

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

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

关于c++ - 在多线程c++中捕获进程的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110853/

相关文章:

c++ - 如何正确使用 setprecision() 将 ".00"添加到金额的末尾?

c++ - C 的替代方案,例如为 C++ 标记和转义嵌套循环

php - 授予 Apache 文件夹权限

c - bsd 或 posix 方式获得首选域 Controller ?

c++ - 正确取消对指针的引用迭代器

c++ - TForm 隐藏在主窗口后面

linux - Varnish +nginx+ISPConfig

linux - 如何将输出附加到文件中?

c++ - 如何在 Linux 中获取 C/C++ 中的用户名?

c - 使用 dup2 时的竞争条件