title: Two-Way Parent Child Communication Using 2 Pipes in C on Linux
body: <p>I'm trying to create a two-way communication between parent and child processes using 2 pipes using C on Linux. The parent is my program and the child is just a random program (say "cat").</p>
  
  <p>I try to uses <code>read()</code> in parent to read child output, but it gives me errno 9, which is Bad file descriptor.</p>
  
  <p>The following is my code</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;errno.h&gt;
  
  #define Read            0
  #define Write           1
  #define ParentRead      read_pipe[1]
  #define ParentWrite     write_pipe[0]
  #define ChildRead       write_pipe[1]
  #define ChildWrite      read_pipe[0]
  
  int main()
  {
      int data_processed;
  
      /** Pipe for reading for subprocess */
      int read_pipe[2];
      /** Pipe for writing to subprocess */
      int write_pipe[2];
  
      char buffer[100];
      memset(buffer, '\0', 100);
  
      if (pipe(read_pipe) == 0 &amp;&amp; pipe(write_pipe) == 0)
      {
          pid_t pid = fork();
          if (pid == (pid_t)-1)
          {
              fprintf(stderr, "Fork failure");
              exit(EXIT_FAILURE);
          }
          else if (pid == (pid_t)0) //Child process
          {
              close(Read);
              close(Write);
              close(ParentRead);
              close(ParentWrite);
              dup(ChildRead);
              dup(ChildWrite);
              execlp("cat", (char*)NULL);
              exit(EXIT_FAILURE);
          }
          else { //Parent process
              close(ChildRead);
              close(ChildWrite);
  
              write(ParentWrite, "abc", 3);
              int r = read(ParentRead, buffer, 99);
              printf("%d %d", r, errno);
              puts(buffer);
          }
      }
  
      exit(EXIT_SUCCESS);
  }
  </code></pre>