0
votes

poll is running for infinite time interval. i want poll to hit when some thing is written into file or when file is updated. but poll is not able to detect when file is written.

        #include <stdio.h>
        #include <poll.h>
        #include <stdlib.h>
        #include <fcntl.h>
        #include <errno.h>
        #include <sys/types.h>
        #include <unistd.h>

        int main() {
                char buf[5]="true";
                struct pollfd ufds[1];
                int rv;
                ufds[0].fd = 0;
                ufds[0].events = POLLIN;
                char *filename="textfile.txt";
                ssize_t ret_write,ret_read;

                ufds[0].fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 5);
                if(ufds[0].fd== -1){
                perror("open");
                return 3; 
                } 

                while(1) {

                        ret_write= write (ufds[0].fd, &buf, (ssize_t) 5);


                        if((rv = poll(ufds, 1,-1 )) == -1) perror("select");
                        else if (rv == 0) printf("Timeout occurred!\n");
                        else if (ufds[0].revents & POLLIN) {
                                printf("return hit\n");
                                read(ufds[0].fd, buf, 5);
                        }
                        fflush(stdout);
                }
                return 0;
        }
1
You cannot use poll for this. You may have better luck with inotify.n. 1.8e9-where's-my-share m.
can u give example how to do it.vivek lala
i tried to use inotify but it works for only directory and not for specified file. i also want inotify to work for ever without using looping statements like while(1){} to avoid thread continuesly running.can u suggest any function which can work only on files continuesly without using while.vivek lala

1 Answers

0
votes

Your example can't work because the file is not open for reading. Even if the file was opened for reading, the code would not work as intended because poll would return sucessfully on end of file.

What you want is the inotify function. Please try it by yourself first, and ask a question when you have code not working as intended.