title: named pipe blocks on writing before its maximum size
body: <p>I try to fill a named pipe (created by <code>mkfifo /tmp/pipe</code>) by writing to it 3 bytes at a time until the <code>write()</code> function blocks.</p>
  
  <p>On my system, a pipe seems to be limited to 16 pages of 4096 bytes. Thus the pipe can contain 65536 bytes.</p>
  
  <p>I do that with the following C code: </p>
  
  <pre><code>int main ()
  {
    pid_t child;
    child = fork ();
    if (child == 0)
      {
        ssize_t ret;
        ssize_t total = 0;
        unsigned char *datat = malloc (65536);
        assert (datat != NULL);
  
        int fd = open ("/tmp/pipe", O_WRONLY);
        assert (fd != -1);
  
        while (1)
        {
          printf ("Trying writting\n");
          ret = write (fd, datat, 3);
          assert (ret != -1);
          total += ret;
          printf ("write : %ld.\n", total);
        }
      }
    else
      {
        int fd = open ("/tmp/pipe", O_RDONLY);
        assert (fd != -1);
        while (1);            //prevent closing the pipe.
      }
    return 0;
  }
  </code></pre>
  
  <p>By this way, I succeed to fill the pipe until 65520 bytes. I don't understand why 65520 and not 65536 (or 65535 if we consider that 65536 is not a multiple of 3). </p>
  
  <p>Then I tried to write 65520 bytes and, after, write 3 bytes:</p>
  
  <pre><code>int
  main (int argc, char *argv[])
  {
    pid_t child;
    child = fork ();
    if (child == 0)
      {
        ssize_t ret;
        ssize_t total = 0;
        unsigned char *datat = malloc (65536);
        assert (datat != NULL);
  
        int fd = open ("/tmp/pipe", O_WRONLY);
        assert (fd != -1);
  
        while(1)
        {
          printf ("Trying writting\n");
          ret = write (fd, datat, 65520);
          assert (ret != -1);
          total += ret;
  
          printf ("Trying writting\n");
          ret = write (fd, datat, 3);
          assert (ret != -1);
          total += ret;
          printf ("write : %ld.\n", total);
        }
  
      }
    else
      {
        int fd = open ("/tmp/pipe", O_RDONLY);
        assert (fd != -1);
        while (1);            //prevent closing the pipe.
      }
    return 0;
  }
  </code></pre>
  
  <p>I expected the second write to block, however it was not the case and I wrote 65523 bytes.</p>
  
  <p>The question is: why can't I write more than 65520 bytes on the first case whereas I can in the second?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>More information :</p>
  
  <ul>
  <li><p>My Operating system is Linux archlinux 4.16.5-1-ARCH</p></li>
  <li><p><code>man 7 pipe</code> give information about the size (which is equal to 65536 bytes) of the pipe and is confirmed by fcntl:</p></li>
  </ul>
  
  <hr>
  
  <pre><code>int
  main (int argc, char *argv[])
  {
    int fd = open ("/tmp/pipe", O_WRONLY);
    printf ("MAX : %d\n", fcntl (fd, F_GETPIPE_SZ));
    return 0;
  }
  </code></pre>