Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file descriptor polling

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

like image 446
Arpit Avatar asked Feb 26 '23 13:02

Arpit


2 Answers

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

like image 142
mvds Avatar answered Mar 03 '23 09:03

mvds


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?

like image 37
Jens Gustedt Avatar answered Mar 03 '23 09:03

Jens Gustedt