title: Restoring stdout after using dup
body: <p>Using <code>fork</code> I created a child and in the child I'm executing the <code>ls</code> command using <code>execl</code>. To send the output to parent,I used <code>pipe</code> and <code>dup</code>. The parent then prints the output. The code gives the expected output, but when I tried to restore back the <code>stdout</code> which I saved initially in <code>stdout_holder</code>, nothing is printed on terminal (when I used printf("hello") or the execl statement below it).
  However after few observations, it is observed that <code>hello</code> is printed only when nothing is done after redirecting "1" for the first time. (If I don't do anything after <code>dup(fd[1],1)</code> and simply do <code>dup(stdout_holder,1)</code> )
  Why is this happening? </p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;sys/types.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;errno.h&gt;
  #include&lt;sys/wait.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;string.h&gt;
  int main()
   {int fd[2],stdout_holder;
   char str;
   pid_t pid;
   pipe(fd);
   pid=fork();
   if(pid==0)
    { stdout_holder=dup(1);
      close(fd[0]);
     printf("stdout_holder=%d\n",stdout_holder); 
     fd[1]=dup2(fd[1],1);
     execl("/bin/ls","ls","-l",NULL);
     stdout_holder=dup2(stdout_holder,1);
     printf("hello\n"); //Terminal doesnt show output.
     execl("/bin/ls","ls","-l",NULL); //Terminal doesnt show output
  
   }
  else
   { close(fd[1]);
     wait(&amp;pid);
     while(read(fd[0],&amp;str,1)&gt;0)
     printf("%c",str);
    } 
  }
  </code></pre>