title: Unix C - Redirecting stdout to pipe and then back to stdout
body: <p>I'm not sure if the following can be done because I cannot find any questions/results via Google on it.  I want to change stdout of a fork() to a pipe, and then change it back to the normal stdout.</p>
  
  <p>This is what I have:</p>
  
  <p>FirstExecutable:</p>
  
  <pre><code>int main()
  {
        int fd[2]; //Used for pipe
        int processID;
  
        if(pipe(fd) == -1)
        {
              printf("Error - Pipe error.\n");
              exit(EXIT_FAILURE);
        }
  
        if((processID = fork()) == -1)
        {
              fprintf(stderr, "fork failure");
              exit(EXIT_FAILURE);
        }
  
        if(processID == 0)
        {
             int newFD = dup(STDOUT_FILENO);
  
            char newFileDescriptor[2];
  
            sprintf(newFileDescriptor, "%d", newFD);
  
            dup2 (fd[1], STDOUT_FILENO);
  
            close(fd[0]);
  
            execl("./helloworld", "helloworld", newFileDescriptor, NULL);
        }
        else
        { 
            close(fd[1]);
  
            char c[10];
  
            int r = read(fd[0],c, sizeof(char) * 10);
  
            if(r &gt; 0)
                 printf("PIPE INPUT = %s", c);
        }
  }
  </code></pre>
  
  <p>helloworld</p>
  
  <pre><code>int main(int argc, char **argv)
  {
        int oldFD = atoi(argv[1]);
  
        printf("hello\n"); //This should go to pipe
  
        dup2(oldFD, STDOUT_FILENO);
  
        printf("world\n"); //This should go to stdout
  }
  </code></pre>
  
  <p>Desired Output:</p>
  
  <pre><code>world
  PIPE OUTPUT = hello
  </code></pre>
  
  <p>Actual Output:</p>
  
  <pre><code>hello
  world
  </code></pre>