title: Close file descriptor
body: <p>I am trying to write so client-server program using 2 pipes, but when I run the following program (server.c):    </p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include "err.h"
  
  #define BUF_SIZE    1024
  
  char message[] = "Hello from your parent!\n";
  char response[] = ""; 
  int main (int argc, char *argv[])
  {
    int fd1 [2];
    int fd2 [2];  
    int buf_len;  
    if (pipe (fd1) == -1) syserr("Error in pipe\n");
    if (pipe (fd2) == -1) syserr("Error in pipe\n");
  
    switch (fork ()) {
      case -1: 
        syserr("Error in fork\n");
  
      case 0:
  
        if (close (0) == -1)       syserr("child, close (0)");
        if (dup (fd1 [0]) != 0)    syserr("child, dup (pipe_dsc [0])");
        if (close (fd1 [0]) == -1) syserr("child, close (pipe_dsc [0])");
        if (close (fd1 [1]) == -1) syserr("child, close (fd1 [1]");
  
        if (close (1) == -1)       syserr("child, close (1)");
        if (dup (fd2 [1]) != 1)    syserr("child, dup (pipe_dsc [1]"); 
        if (close (fd2 [1]) == -1) syserr("child, close (pipe_dsc [1])");
        if (close (fd2 [0]) == -1) syserr("chiled, close (fd2 [0]");
  
        execl("./client", "client", (char*) 0); 
        syserr ("child, execvp");
  
        exit (0);
  
      default:
  
        printf("%d\n", fd1[0]);
        printf("%d\n", fd1[1]);
        printf("%d\n", fd2[0]);
        printf("%d\n", fd2[1]);
        if (close (fd1[0] != -1)) syserr("parent, close (fd1[0])");
        if (close (fd2[1] != -1)) syserr("parent, close (fd2[1])");
        while (fgets(message, sizeof(message), stdin) != NULL) {
            if (write (fd1 [1], message, sizeof(message) - 1) == -1) 
                syserr("write");
            if ((buf_len = read(fd2[0], response, BUF_SIZE -1)) == -1) 
                syserr("Error in read");
            printf("%s%s", "response: ", response);
        }   
  
        if (close (fd1 [1]) == -1) syserr("parent, close (pipe_dsc [0])");
        if (close (fd2 [0]) == -1) syserr("parent, close (pipe_dsc [1])");
  
        if (wait (0) == -1)
            syserr("wait");
        exit (0);
    } /* switch (fork ()) */
  }
  </code></pre>
  
  <p>And client.c</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdbool.h&gt;
  #include "err.h"
  
  #define BUF_SIZE                1024
  
  int main (int argc, char *argv[])
  {
      char buf[BUF_SIZE];
      while (fgets(buf, sizeof(buf), stdin) != 0) {
          printf("%s%s","Write to stdout",  buf);
      }   
      return 0;
  }
  </code></pre>
  
  <p>I got the following mistake:</p>
  
  <pre><code>3
  4
  5
  6
  ERROR: parent, close (fd2[1]) (9; Bad file descriptor)
  </code></pre>
  
  <p>Any idea why I can't close descriptor?</p>
  
  <p>Thnaks in advance.</p>