title: Unix Piping using Fork and Dup
body: <p>Let's say within a program I want to execute two processes, one to execute a <code>ls -al</code> command, then piping the result into the <code>wc</code> command, and displaying the output on the terminal. How can I do this using pipe file descriptors? So far the code I have written:</p>
  <pre class="lang-c prettyprint-override"><code>int main(int argc, char* argv[]) {
      int pipefd[2];
      int pipefd2[2];
  
      pipe(pipefd2);
      if ((fork()) == 0) {
         dup2(pipefd2[1], STDOUT_FILENO);
         close(pipefd2[0]);
         close(pipefd2[1]);
         execl(&quot;ls&quot;, &quot;ls&quot;, &quot;-al&quot;, NULL);
         exit(EXIT_FAILURE);
      } 
  
      if ((fork()) == 0){
          dup2(pipefd2[0], STDIN_FILENO);
          close(pipefd2[0]);
          close(pipefd2[1]);
          execl(&quot;/usr/bin/wc&quot;, &quot;wc&quot;, NULL);
          exit(EXIT_FAILURE);
      }
      close(pipefd[0]);
      close(pipefd[1]);
      close(pipefd2[0]);
      close(pipefd2[1]);
  }
  </code></pre>
  <p>An example would be greatly helpful.</p>