0

when I use this simple program to get the standard output of the process, I also somehow get the standard error of the process, although the man page for popen says that only the standard output is redirected. Is it possible that this is related to the shell that is used when forking a process with popen? errEr is a simple program outputting to stderr (cerr << "hello";). I'm using RHEL 6.4. Thanks!

#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;
}
hovnatan
  • 1,331
  • 10
  • 23
  • What's `errWr`? Does it actually output anything to `stderr`? – P.P Apr 01 '15 at 12:10
  • its just a simple program outputting to `stderr` ( `cerr << "hello";`) – hovnatan Apr 01 '15 at 12:12
  • Are you sure that your program print to `stderr`? Maybe it's just output directly from `errWr`? Maybe you should try to append something in your program, to be able to distinguish the outputs. Something like `cout << "=>" << str << "<=" << endl;` – tmp Apr 01 '15 at 12:18
  • Possible duplicate http://stackoverflow.com/questions/6900577/c-popen-wont-catch-stderr – Jose Palma Apr 01 '15 at 12:18
  • 1
    Are you sure you're not just receiving stderr as normal, rather than via the pipe? – teppic Apr 01 '15 at 12:22
  • 1
    You could avoid the `stderr` being printed by redirecting it: `FILE *fd = popen("errWr 2>/dev/null", "r");` – P.P Apr 01 '15 at 12:28
  • 1
    It's not a good thing to mix `` and `` calls in a program. Both use buffered streams and possible undefined behaviour can arise of mixing them all. – Luis Colorado Apr 02 '15 at 08:22

1 Answers1

2

You're not getting the output from stderr in your program using popen.

Following simple example shows, that error stream from started application is printed in terminal, without being read in your program. popen redirects only stdout stream and stderr stream is not affected, so it's just printed to terminal.

#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;
}
tmp
  • 1,079
  • 9
  • 16