title: Weird behaviour of FIFO reading/writing in C
body: <p>I've got a C program that reproduces a server using FIFOs. The program reads two lines from an input FIFO — a number <code>n</code> and a string <code>str</code>— and writes on an output FIFO <code>n</code> lines, each of which is a single occurrence of <code>str</code>. I wrote the following code.</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;ctype.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/stat.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;string.h&gt;
  
  #define MAX_SIZE 256
  
  char *readline(int fd, char *buffer) {
      char c;
      int i = 0;
      while (read(fd, &amp;c, 1) != 0) {
          if (c == '\n')
              break;
          buffer[i++] = c;
      }
      return buffer;
  }
  
  int main(int  argc, char** argv) {
      mkfifo(argv[1], 0666);
      mkfifo(argv[2], 0666);
      int in = open(argv[1], O_RDONLY);
      int out = open(argv[2] ,O_WRONLY);
  
      char line[MAX_SIZE];
      memset(line, 0, MAX_SIZE);
      int n, i;
      while (1) {
          strcpy(line, readline(in, line));
          sscanf(line, "%d", &amp;n);
          strcpy(line, readline(in, line));
  
          for (i = 0; i &lt; n; i++) {
              write(out, line, strlen(line));
              write(out, "\n", 1);
          }
      }
      close(in);
      close(out);
  
      return 0;
  }
  </code></pre>
  
  <p>This program compiles and runs with no errors, but it outputs a different number of occurrences of the string at each execution. For example, if the two input lines in the input FIFO are <code>5\nhello</code>, it then prints out from 1 to 25 occurrences of <code>hello</code> at each run (frequency appears to be completely random).</p>
  
  <p>I've been stuck on this for two days. Please give me some help.</p>