clinuxpipefilesize

How to get available data in a pipe in linux


In Linux, after writing some data in a pipe (yet not read), when using fstat on read/write side of a pipe, the st_size field is zero. Is it possible to get the size of data available in a pipe?

Sample code:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>

#define BUFLEN  8

int main() {
        char            buf[BUFLEN];
        int             fd[2];
        struct stat     sb;

        pipe(fd);

        write(fd[1], buf, BUFLEN);

        fstat(fd[1], &sb);                        // the same for fd[0]

        printf("pipe size=%ld\n", sb.st_size);    // print 0


        exit(0);
}

Solution

  • Man page pipe(7) says the following:

       The following ioctl(2) operation, which can be applied to a file
       descriptor that refers to either end of a pipe, places a count of
       the number of unread bytes in the pipe in the int buffer pointed
       to by the final argument of the call:
    
           ioctl(fd, FIONREAD, &nbytes);
    
       The FIONREAD operation is not specified in any standard, but is
       provided on many implementations.
    

    So some systems have non-standard ioctl operation for getting the number of unread bytes in the pipe.