2

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;
}
onemach
  • 4,265
  • 6
  • 34
  • 52
user1089679
  • 2,328
  • 8
  • 41
  • 51
  • 2
    `2>&1` redirects the `stderr` output to `stdout`, so the messages to the error stream are received in the standard output stream. If you are running this on a console, generally `stderr` & `stdout` both output to the console. – another.anon.coward Dec 28 '11 at 04:17
  • means using 2>&1 we can convert error messages to stdout messages? – user1089679 Dec 28 '11 at 04:25
  • @user1089679 no convert..it means we redirect output of stderr to stdout – Jeegar Patel Dec 28 '11 at 04:37
  • Not convert, it redirects. There are separate streams for input, output & error. If you want to print error message, it is generally printed onto `stderr` (like in case of `fprintf`). If you redirect, such messages are also seen on `stdout`. To see this effect, change `ping 4.2.2.2` to say `ping 344.2.2.2` which is error. Now run the program as `./a.out 2>/dev/null`. Now try out with & without `2>&1`, you will see the effect to using `2>&1` & not using it. – another.anon.coward Dec 28 '11 at 04:37

1 Answers1

1

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.

Community
  • 1
  • 1
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98