title: how to control popen stdin, stdout, stderr redirection?
body: <p>I am confused about how popen() redirects stdin, stdout and stderr of the child process in unix. The man page on popen() is not very clear in this regard. The call</p>
  
  <pre><code>FILE *p = popen("/usr/bin/foo", "w");
  </code></pre>
  
  <p>forks a child process and executes a shell with arguments "-c", "/usr/bin/foo", and redirects stdin of this shell (which is redirected stdin of foo), stdout to p. But what happens with stderr? What is the general principle behind it?</p>
  
  <p>I noticed that, if I open a file in foo (using fopen, socket, accept etc.), and the parent process has no stdout, it gets assigned the next available file number, which is 1 and so on. This delivers unexpected results from calls like fprintf(stderr, ...).</p>
  
  <p>It can be avoided by writing</p>
  
  <pre><code>FILE *p = popen("/usr/bin/foo 2&gt;/dev/null", "w");
  </code></pre>
  
  <p>in the parent program, but are their better ways?</p>