Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 2>&1 do to popen?

Tags:

c

popen

2>&1 causes popen to trap the stderr.

I want to understand how does it work.

What roles do 2, >, &, 1 play here?
What do I need to study to understand them?

like image 614
Aquarius_Girl Avatar asked Jan 07 '23 23:01

Aquarius_Girl


1 Answers

It's a shell construct. It means redirect (>) stderr(2) to wherever stdout(1) goes. 1 is file the stdout's file descriptor and 2 is the stderr's file descriptor.

$ command 2>&1 #redirect stderr to stdout

$ command 1>&2 #redirect stdout to stderr

$ command 1>output 2>errors #redirect stdout to a file called "output"
                            #redirect stderr to a file called "errors"

popen() captures only stdout. So running a command using can't capture the messages from its stderr.

For example, with

  FILE *fp = popen("command", "r");

only stdout of command can be captured (read using fp). But with this

  FILE *fp = popen("command 2>&1", "r");

stdout and stderr are captured. But with this redirection, stdout is indistinguishable from stderr as they both are mixed.


The effect is doing same as dup2(1,2); in C.

Consider

#include <stdio.h>
#include <unistd.h>

int main(void)
{
   dup2(1,2);
   fprintf(stdout, "printed to stdout\n");
   fprintf(stderr, "printed to stderr\n");
}

If this is compiled and run as:

# ./a.out >output

Both lines will be printed to a file called output.

If run the code by commenting out the dup2() line. Now only the first line will be printed to the file and second line will be printed on the console even it captures only the stdout using redirection (>).

Additional sources:

  • https://www.gnu.org/software/bash/manual/html_node/Redirections.html
  • http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html
  • https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true
like image 151
P.P Avatar answered Jan 15 '23 01:01

P.P