title: Exec after forking a process doesn't return the result before the program finishes
body: <p>I'm trying to make a program that forks once and while the parent waits for the child terminates, this child forks again and then executes two execs. There is a Pipe on the program and I've checked the return values of every dup2() and pipe() on the program -just omitted them here to make it looks more concise-. The problem is that I only get the result of ls -a | sort -r AFTER the program finishes.
  The code is:</p>
  
  <pre><code>#include &lt;cstdio&gt;
  #include &lt;cstring&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;errno.h&gt;
  
  int main(int argc, char *argv[]) {
  printf("Shell&gt; \n"); fflush(stdout);
  
  pid_t pid1;
  pid_t pid2;
  int status = 0;
  int fd[2];
  
  if(pipe(fd) &lt; 0) {
      printf("FATAL ERROR.\n");
  }   
  
  pid1 = fork();
  
  if(pid1 &gt; 0) {      // Parent
      waitpid(pid1, &amp;status, 0);
      printf("\t\t------PID1 Complete-------\n\n");                   
  }
  else {              // Child
      if(pid1 == 0) {
          printf("ON CHILD\n");
  
          pid2 = fork();
  
          if(pid2 &gt; 0) {  // Child -&gt; Parent
              printf("ON CHILD-Parent\n");
              close(fd[1]);
              dup2(fd[0], STDIN_FILENO);
              waitpid(pid2, &amp;status, 0);
              printf("ON CHILD-Parent after wait\n");
              execlp("sort", "sort", "-r", NULL);
              perror("Problem with execlp\n");
              exit(1);
          }
          else {          // Child -&gt; Child
              printf("ON CHILD-&gt;Child\n");
              close(fd[0]);
              dup2(fd[1], STDOUT_FILENO);
              execlp("ls", "ls", "-a", NULL);
              perror("Problem with execvp\n");
              exit(1);
          }               
      }   // End of if(pid1 == 0)
  }   // End of Child
  
  printf("\nEnd of program.\n");
  
  return 0;
  }
  </code></pre>
  
  <p>My current output is:</p>
  
  <pre><code>Shell&gt; 
  ON CHILD
  ON CHILD-Parent
  ON CHILD-&gt;Child
  ON CHILD-Parent after wait
  </code></pre>
  
  <p>I think the problem is on the waits, but I just can't figure out how to make this work. Any ideas? Thanks!</p>