title: implementing pipeline using fork and pipe
body: <p>I need to implement nameless pipes using fork for my OS class but I cant get it to work. Its a simple code and have nothing special in it but I just dont get anything. Im trying to run 
  ls -l | wc -l but I get 0 everytime. </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;dirent.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;fcntl.h&gt; // for open flags
  #include &lt;time.h&gt; // for time measurement
  #include &lt;assert.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;string.h&gt;
  
  int pid,status;
  int pipefd[2];
  
  void my_exec(char* cmd, char** argv)
  {
      pipe(pipefd);     // Fixed
      pid = fork();
      // pipe(pipefd);  // Original
  
      if(pid==0){
          close(pipefd[0]);
          dup2(pipefd[1],fileno(stdout));
          close(pipefd[1]);
          execvp(cmd, argv);
  
  
      }
      else {
          close(pipefd[1]);
          dup2(pipefd[0],fileno(stdin));
          while(wait(&amp;status)!=-1);
          close(pipefd[0]);
          return; 
      }
  
  }
  
  int main(int argc, char** argv)
  {
      assert(strcmp(argv[argc-1], "-"));
  
      int i;
      for (i = 1; i &lt; argc; ++i) {
          if (!strcmp(argv[i], "-")) {
              argv[i] = NULL;
              my_exec(argv[1], &amp;argv[1]);
              argv = &amp;argv[i];
              argc -= i;
              i = 0;
          }
  
      }
  
      char* args[argc];
      args[argc-1] = NULL;
      for (i = 1; i &lt; argc; ++i) {
          args[i-1] = argv[i];
  
      }
  
      if (execvp(args[0], args) == -1)
          perror("execvp failed");
      return;
  }
  </code></pre>
  
  <p>btw the input for the command Im trying is ls -l - wc -l (instead of | type -)</p>
  
  <p>OK Duck solved it: i should create the pipe before the fork, updated.</p>