title: Reading and writing data through a pipe
body: <p>I have created two processes using fork(). The child process is producing and writing continuously a variable amount of data (array char) to the pipe. The parent process reads from the pipe and prints the received data to stdout.</p>
  
  <p>The code is very simple:</p>
  
  <pre><code>switch (fork()) {
    case -1: 
      exit (1);
      break;
    case 0:
      close(fd[0]);
      generate_data(fd[1]);
      break;
    default:
      close(fd[1]);
      while(1) {
          n = read(fd[0], readbuffer, sizeof(readbuffer));
          readbuffer[n] = 0;
          if (n &gt; 0)
              printf ("read: %s\n", readbuffer);            
          else
              exit(1);
      }   
     break;
  }   
  </code></pre>
  
  <p>Where <code>generate_data(int)</code> iterates over a list, writing each element (string) to the file descriptor given as argument (the write end of the pipe in this case):</p>
  
  <pre><code>void generate_data(int fd) 
  {
     node_t node* = list;
     while (node != NULL) {
       write(fd, node-&gt;data, strlen(node-&gt;data)+1);
       node = node-&gt;next();
     }
  
  }
  </code></pre>
  
  <p>The problem here is that the output is always unpredictable: the child process writes data to the pipe when the other process is processing the last <code>read</code>, so when it calls to read again the rest of the data is not there anymore.</p>
  
  <p>According to <code>man 2 pipe</code>, this shouldn't be happening:</p>
  
  <blockquote>
    <p>Data written to the write end of the pipe is buffered by the 
    kernel until it is read from the read end of the pipe.</p>
  </blockquote>
  
  <p>Taking a list of 10 elements, some output examples:</p>
  
  <p>Example 1:</p>
  
  <pre><code>read: element_4
  read: element_8
  read: element_9
  </code></pre>
  
  <p>Example 2:</p>
  
  <pre><code>read: element_7
  read: element_8
  read: element_9
  read: element_10
  </code></pre>
  
  <p>Example 3:</p>
  
  <pre><code>read: element_2
  read: element_8
  </code></pre>
  
  <p>Anyone has any idea what's happening here?</p>