How to flush a file descriptor without blocking

From Applied Optics Wiki
Revision as of 15:58, 21 January 2009 by Matt (talk | contribs) (New page: 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 yo...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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){
int n,m;
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((n=select(fd+1,&rd,NULL,NULL,&t))){
                m=read(fd,buff,100);
                //buff[m]='\0';
                //printf("The fifo had %s stuck in it, cleared\n");
                }
        }

Matt