title: C - Redirecting awk/sed stdout to pipe doesn't work
body: <p>So I have an exercise to do, and one part of this exercise requires us to execute a command passed as an argument, be able to pass it some strings on stdin, and get its output on stdout and stderr.
  How I did it, I need to redirect the stdout and stderr (of the child, which is gonna call an exec) to a couple of pipes (other end of the pipes is held open by the parent).
  I managed to do it, when I ask it to execute bash and send it &quot;ls&quot;, it gives me what i want, where i want it. Same with cat and others.
  Problem is, when I try executing awk or sed, nothing is ever written on the pipe. Ever.
  If i leave stdout untouched, it does print it how it should. But as soon as i redirect the stdout, nothing.
  I tried everything, select(), wait(), sleep() (even though it's not allowed). Nothing seems to work.</p>
  <p>I made a minimum working example of what i mean (clearly, it lacks of conventions and mindful writing, as free() and close(), but it does it's job) which Is the one I'm attaching. The code works when i call it like this:
  <code>./program $(which bash)</code>
  It prompts for something, i write &quot;ls&quot; and it gives me the result expected
  but when i try
  <code>./program $(which awk) '{print $0;}'</code>
  I get nothing at all</p>
  <p>Here's the code (minimum working example):</p>
  <pre><code>#define _GNU_SOURCE
  #include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;sys/time.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;errno.h&gt;
  
  int main(int argc, char* argv[]){
      int fdStdinP[2],fdStdoutP[2];
      char *string,*array[3];
      array[0]=argv[1];
      array[1]=argv[2];
      array[2]=0;
      pipe(fdStdinP);
      pipe(fdStdoutP);
      int pid=fork();
      if(pid==0){
          close(fdStdinP[1]);
          close(fdStdoutP[0]);
          dup2(fdStdinP[0],0);
          close(fdStdinP[0]);
          dup2(fdStdoutP[1],1);
          close(fdStdoutP[1]);
          //as suggested, the file descriptors are now closed
          execvp(argv[1],array);
          perror(&quot;&quot;);
          return 0;
      }
      close(fdStdinP[0]);
      close(fdStdoutP[1];
      string=calloc(1024,sizeof(char));
      read(0,string,1024);
      write(fdStdinP[1],string,1024);
      free(string);
      string=calloc(1024,sizeof(char));
      read(fdStdoutP[0],string,1024);
      printf(&quot;I have read:%s&quot;,string);
      return 0;
  }
  </code></pre>
  <p>Thank you for your time.</p>