title: Read and Write operations get bad fd and no such file
body: <p>I have this C program.
  I have two processes, father and son, and use semaphores to make them synchronize one at time. 
  The father has to write (n) numbers, ten in this case, always in the first byte of the opened file and the son has to read it.
  The problem is that when I print the results, I get bad file descriptor for the write (father) and no such file for the read(the son).
  Can you help me, please?? Thank you</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;semaphore.h&gt;
  
  #define FILENAME "test.txt"
  #define MUTEX "/mutex"
  #define READ "/read"
  #define WRITE "/write"
  
  int main(int argc, char *argv[]){
      int i, pid, n=10, fd, x;
      int nread, nwrite;
      char c = 'a';
      sem_t *mutex, *reader, *writer;
  
      //fd = open(FILENAME, O_CREAT | O_TRUNC, 0666);
      mutex = sem_open(MUTEX, O_CREAT, 0666, 1);
      reader = sem_open(READ, O_CREAT, 0666, 0);
      writer = sem_open(WRITE, O_CREAT, 0666, 1);
      pid = fork();
      fd = open(FILENAME, O_CREAT | O_TRUNC, 0777);
      if(fd &lt; 0){
          perror("Open FILE error");
          exit(-1);}
      if(pid == 0){   // son
          do{
              sem_wait(reader);    // si può leggere???
              sem_wait(mutex);
              lseek(fd, 0, SEEK_SET);
              nread = read(fd, &amp;x, sizeof(int));
              if(nread &lt;=0)
                  perror("Read error");
              printf("Son has read (%d byte) = %d\n", nread, x);
              fflush(NULL);
              sem_post(mutex);
              sem_post(writer);
          }
          while(x != (n-1));
          exit(0);
      }
      else{
          for(i=0; i&lt;n; i++){
              sem_wait(writer);  // can I write??
              sem_wait(mutex);
              lseek(fd, 0, SEEK_SET);
              nwrite = write(fd, &amp;c, sizeof(char));
              if(nwrite &lt;= 0)
                  perror("nwrite error");
              printf("Father has written (%d byte) %d\n", nwrite, i);
              fflush(NULL);
              sem_post(mutex);
              sem_post(reader);    // it's possible to read
          }
          //wait(NULL);
      }
      sem_unlink(MUTEX);
      sem_unlink(READ);
      sem_unlink(WRITE);
      //remove(FILENAME);
  
      exit(0);
  }
  </code></pre>