【问题标题】:C++ read popen error output into string [duplicate]C ++将popen错误输出读入字符串[重复]
【发布时间】:2017-06-21 15:21:29
【问题描述】:

我正在通过 posix popen() 函数打开一个进程。例如。 git push、mkdir x 等

我可以通过将这些命令的输出存储到这样的缓冲区中轻松读取:

#include <iostream>
#include <stdio.h>

using namespace std;

int main() {

FILE *in;
char buff[512];

if(!(in = popen("mkdir x", "r"))){
    return 1;
}

// fgets stores the output into buff
while(fgets(buff, sizeof(buff), in)!=NULL){
    cout << buff;
}
pclose(in);

return 0;

}

但是,如果过程出现错误,例如mkdir 失败,然后我想将错误读入字符串或字符缓冲区。

但是,对于上面的代码,如果失败,错误不会存储在缓冲区中。我认为是因为错误被重定向到标准错误而不是标准输入。

如何修改上面的代码得到bash/进程返回的错误信息?

【问题讨论】:

    标签: c++


    【解决方案1】:

    你可以在popen方法调用中指定重定向:

    popen("mkdir x 2>&1", "r")
    

    然后您就可以从缓冲区中读取错误消息。

    【讨论】:

    • 这是否仍会将正常输出(如果没有错误)捕获到缓冲区中?
    • @DramaticStackoverflowPirate 是的。 2&gt;&amp;1 表示将 stderr (2) 写入 stdout (1) 但不会丢弃 stdout,它有效地结合了两者。
    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多