title: Trouble with dup2, stdout, and stderr
body: <p>When this program is run, the "stderr" line is displayed before the "stdout" line. Why? I thought dup2 would make stderr and stdout use the same file descriptor so there should be no problem with buffering. I'm using gcc 3.4.6 on Solaris 10.</p>
  
  <pre><code>#include &lt;errno.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  
  int main()
  {
      int fd[2];
      int pid;
      char buf[256];
      int n;
  
      if(pipe(fd) &lt; 0) {
          perror("pipe");
          return 1;
      }
      if((pid = fork()) &lt; 0) {
          perror("fork");
          return 1;
      }
      else if(pid &gt; 0) { // parent
          close(fd[1]);
          if((n = read(fd[0], buf, sizeof(buf))) &gt; 0) {
              buf[n] = 0;
              printf("%s", buf);
          }
      }
      else {
          dup2(fd[1], fileno(stdout));
          dup2(fd[1], fileno(stderr));
          close(fd[1]);
          fprintf(stdout,"stdout\n");
          fprintf(stderr,"stderr\n");
      }
      return 0;
  }
  </code></pre>