title: How do you use dup2 and fork together?
body: <p>I'm taking an operating systems course and I'm having a hard time how input is redirected with dup2 when you have forks. I wrote this small program to try and get a sense for it but I wasn't successful in passing the output of a grand-child to a child. I am trying to mimick the unix command: ps -A | wc -l. I'm new to Unix, but I believe this should count the lines of the list of running processes I get. So my output should be a single number.</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  int main( int argc, char *argv[] )  {
  
      char *searchArg = argv[ 1 ];
      pid_t pid;
  
      if ( ( pid = fork() ) &gt; 0 ) {
          wait( NULL );
          cout &lt;&lt; "Inside parent" &lt;&lt; endl;
      } 
      else if ( pid == 0 ) {
              int fd1[ 2 ];
              pipe( fd1 );
              cout &lt;&lt; "Inside child" &lt;&lt; endl;
  
              if ( pid = fork() &gt; 0 ) {
                  dup2( fd1[ 0 ], 0 );
                  close( fd1[ 0 ] );
                  execlp( "/bin/wc", "-l", NULL );
              }
              else if ( pid == 0 ) {
                  cout &lt;&lt; "Inside grand child" &lt;&lt; endl;
                  execlp( "/bin/ps", "-A", NULL );
              }
          }
      return 0;
  }
  </code></pre>
  
  <p>I don't have it in the code above, but here is my guess on how things should go down:</p>
  
  <ul>
  <li>We need to redirect standard output of command ps -A (whatever is usually printed to the screen, correct?) so that the wc -l command can use it to count the lines.</li>
  <li>This standard output can be redirected using dup2, like dup2( ?, 1 ) which means redirect standard output to ?. Then you close ?.</li>
  </ul>
  
  <p>Question: Where do I redirect it to? I know it should be one of the file descriptors, but where should it be redirected so that wc can process it?</p>
  
  <ul>
  <li>wc somehow receives the standard output.</li>
  </ul>
  
  <p>Question: How does wc receive the output? Through an execlp parameter? Or does the operating system check one of the file descriptors?</p>
  
  <ul>
  <li>Execute wc -l.</li>
  </ul>
  
  <p>Which one of these is closed and left open for wc to receive and process ps's output? I keep thinking this needs to be thought of backwards since ps needs to give its output to wc...but that doesn't seem to make sense since both child and grand-child are being processed in parallel.</p>
  
  <p><img src="https://i.stack.imgur.com/ybgHh.jpg" alt="pipe dream"></p>