0

I'm opening a process via the posix popen() function. E.g. git push, mkdir x, etc.

I can read the output from these commands easily by storing it into a buffer like this:

#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;

}

But then if there is an error with the process, e.g. mkdir fails, then I want to read the error into a string or character buffer.

However, with the code above, if it fails, the error isn't stored in the buffer. I think it is because the error is redirected to standard error instead of standard input.

How do I modify the code above to get the error message returned by bash/the process?

1 Answers1

6

You can specify redirection in the popen method call:

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

You'd then be able to read the error message from the buffer.

Anew
  • 5,175
  • 1
  • 24
  • 36
  • 1
    Would this still capture the normal output (if there are no errors) into the buffer? –  Jun 21 '17 at 15:32
  • 2
    @DramaticStackoverflowPirate yes. `2>&1` means write stderr (2) to stdout (1) but it doesn't drop stdout, it effectively combines combines the two. – Ryan Haining Jun 21 '17 at 15:35