title: Close pipes get Bad file descriptor
body: <p>Here is the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;dirent.h&gt;
  
  int main(int argc, char **argv) {
  
  int num = 2;
  pid_t pid;
  int i;
  
  int p1[num][2], p2[num][2];
  for (i = 0; i &lt; num; i++) {
      if (pipe(p1[i]) == -1) {
          perror("pipe");
          exit(1);
      }
      if (pipe(p2[i]) == -1) {
          perror("pipe");
          exit(1);
      }
  }
  
  for (i = 0; i &lt; num; i++) {
      if ((pid = fork()) == 0) {
          if (close(p1[i][1]) != 0) {
              perror("close");
              exit(1);
          }
          if (close(p2[i][0]) != 0) {
              perror("close");
              exit(1);
          }
          printf("%d\n", getpid());
          exit(0);
      } else if (pid &gt; 0) {
          if (close(p1[i][0]) != 0) {
              perror("close");
              exit(1);
          }
          if (close(p2[i][1]) != 0) {
              perror("close");
              exit(1);
          }
          continue;
      } else {
          perror("fork");
          exit(1);
      }   
  }
  
  for (i = 0; i &lt; num; i++) {
      if (close(p1[i][0]) != 0) {
          perror("close1"); // &lt;----error
      }
      if (close(p1[i][1]) != 0) {
          perror("close");
      }
      if (close(p2[i][0]) != 0) {
          perror("close");
      }
      if (close(p2[i][1]) != 0) {
          perror("close2"); // &lt;----error
      }
  }
  for (i = 0; i &lt; num; i++) {
      if (wait(NULL) == -1) {
          perror("wait");
          exit(1);
      }
  }
  return 0;
  }
  </code></pre>
  
  <p>When I run this, it gives me this output</p>
  
  <pre><code>close1: Bad file descriptor
  close2: Bad file descriptor
  close1: Bad file descriptor
  close2: Bad file descriptor
  8798
  8799
  </code></pre>
  
  <p>What I'm trying to do is to create two 2D array of pipes and fork num times.
  The creating and running are working well, but some pipes can't close.
  It seems that p1[i][0] and p2[i][1] are never closer properly.</p>