Reputation: 2368
Here I got one program from somewhere to read output of a system call from the console.
But to fetch error messages I used 2>&1
in fp = popen("ping 4.2.2.2 2>&1", "r");
this line instead of fp = popen("ping 4.2.2.2", "r");
So could anybody explain me Whats the significant of 2>&1
in above line.
Here is my code.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
int status;
char path[1035];
/* Open the command for reading. */
fp = popen("ping 4.2.2.2 2>&1", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
}
/* close */
pclose(fp);
return 0;
}
Upvotes: 2
Views: 203
Reputation: 16597
0=stdin
; 1=stdout
; 2=stderr
If you do 2>1
that will redirect all the stderr
to a file named 1
. To actually redirect stderr
to stdout
you need to use 2>&1
. &1
means passing the handle to the stdout
.
This has been discussed here in detail.
Upvotes: 1