views:

81

answers:

2

Hi, I have created a following program in which I wish to poll on the file descriptor of the file that I am opening in the program.

#define FILE "help"

int main()
{
        int ret1;
        struct pollfd  fds[1];

        ret1 =  open(FILE, O_CREAT);

        fds[0].fd = ret1;
        fds[0].events = POLLIN;

        while(1)
        {
                poll(fds,1,-1);

                if (fds[0].revents & POLLIN)
                        printf("POLLING");
        }
        return 0;
}

It is going in infinite loop. I am expecting to run the loop when some operation happen to the file. (Its a ASCII file) plz help

+2  A: 

poll() actually doesn't work on opened files. Since a read() on a file will never block, poll() will always return that you can read non-blocking from the file.

This would (almost) work on character devices*, named pipes** or sockets, though, since those block when you read() from them when there is no data available. (you also need to actually read that data then, or else poll will tell again and again that data is available)

To "poll" a growing/shrinking file, see man inotify or implement your own polling using fstat() in a loop.

* block devices are a story apart; while technically a read from a harddisk can block for 10 ms or longer, this is not perceived as blocking I/O in linux.
** see also how to flush a named pipe using bash

mvds
Can you please explain "your own polling using fstat() in a loop".
Arpit
Try `strace tail -f somefile` - it just sleeps 1 second and then checks with fstat if the file has grown.
mvds
+1  A: 

No idea if this is the cause of your problems (probably not), but it is a particularly bad idea to redefine the standard macro FILE. Didn't your compiler complain about this?

Jens Gustedt