在 C++ 中使用 popen 时的 stderr 输出 linux

stderr output when using popen in C++ linux

当我使用这个简单的程序获取进程的标准输出时,我也以某种方式得到了进程的标准错误,尽管 popen 的手册页说只有标准输出被重定向。这是否可能与使用 popen 分叉进程时使用的 shell 有关? errEr 是一个输出到 stderr (cerr << "hello";) 的简单程序。我正在使用 RHEL 6.4。谢谢!

#include <iostream>
#include <cstdio>

using namespace std;

int main ()
{
    FILE *fd = popen("errWr", "r");
    char str [1024];
    while (fgets(str, 1024, fd))
    {
        cout<<str<<endl;
    }
    return 0;
}

您没有在程序中使用 popenstderr 获得输出。

下面的简单示例显示,启动应用程序的错误流打印在终端中,而不是在您的程序中读取。 popen 仅重定向 stdout 流并且 stderr 流不受影响,因此它只是打印到终端。

#include <iostream>
#include <cstdio>

using namespace std;

int main ()
{
    FILE *fd = popen("errWr", "r");
    char str [1024];
    while (fgets(str, 1024, fd))
    {
        cout << "=>" << str << "<=" << endl;
    }
    return 0;
}