How to flush a file descriptor without blocking

From Applied Optics Wiki
Jump to: navigation, search

This problem came up and there seemed no simple way to overcome it. The obvious method of using streams instead of file descriptors (which gives you access to fflush()) doesn't help if you are trying to flush a input (read()). Plus it can have disadvantages for the rest of your code (eg you want non-blocking reads of unknown length on a FIFO or pipe (read(fd,&data,100) returns when all the data or 100 bytes has been read whereas fread(&data,1,100,fi); doesn't return until it has 100 bytes).

Anyway I couldn't find a simple answer in standard libraries so I wrote this:


void flush_read_fd(int fd){
fd_set rd;
struct timeval t;
char buff[100];
        t.tv_sec=0;
        t.tv_usec=0;
        FD_ZERO(&rd);
        FD_SET(fd,&rd);
        while(select(fd+1,&rd,NULL,NULL,&t)){
                read(fd,buff,100);
                }
        }

It works nice for me and solves a problem where a FIFO is used in a client / server model and the client is killed mid read leaving unwanted data in the FIFO.

Matt