title: C - exec not outputting into pipe
body: <p>I am making a program that will eventually be able to work for (theoretically) any shell command passed to it. My problem is that the exec that runs will not put its output into the pipe, and instead when run it seems as if the initial call is going into the pipe instead? I tried flushing the stdout first but it will not work. Any help is appreciated!</p>
  
  <pre><code>int main(int argc, char *argv[]) {
  
      int i=0, pid;
      int dataPipe[2];
      pipe(dataPipe);
  
      char *newArgs[5] = {"/bin/sh", "-c", "ls", "-a", NULL};
  
      if ((pid = fork()) &lt; 0) {
  
          printf("Error: could not fork!");
          exit(2);
      }
  
      else if (pid == 0) {
  
          close(dataPipe[0]);
          fflush(stdout);
  
          dup2(dataPipe[1], 1);
          close(dataPipe[1]);
  
          if (execvp(newArgs[0], newArgs) &lt; 0) {
  
              printf("Command Failed to exucute!");
              exit(3);
          }
      }
  
      else {
  
          char buf[BUFFER];
          close(dataPipe[1]);
  
          wait(0);
          printf("Command exexuted correctly!\n");
  
          while(read(dataPipe[0], buf, BUFFER) != 0) {
              printf("Here is the command's output:\n%s\n", buf);
          }
  
          exit(0);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Here is the output:</p>
  
  <pre><code>$ ./doit ls -a                                       
  Command exexuted correctly!
  Here is the command's output:
  d
  @
  Here is the command's output:
  o
  @
  Here is the command's output:
  i
  @
  Here is the command's output:
  t
  @
  Here is the command's output:
  @
  Here is the command's output:
  d
  @
  Here is the command's output:
  o
  @
  Here is the command's output:
  i
  @
  Here is the command's output:
  t
  @
  Here is the command's output:
  .
  @
  Here is the command's output:
  c
  @
  Here is the command's output:
  
  
  @
  </code></pre>