How to track file descriptor for new data availability?

Consider the following code snippet.

#include <fcntl.h> #include <stdio.h> #include <sys/poll.h> #include <unistd.h> int main(int argc, char ** argv) { int fd; char buf[1024]; int i; struct pollfd pfds; fd = open(argv[1], O_RDONLY); while (1) { pfds.fd = fd; pfds.events = POLLIN; poll(&pfds, 1, -1); if (pfds.revents & POLLIN) { i = read(fd, buf, 1024); write(1, buf, i); } } return 0; } 

This program gets the file name, opens the corresponding file and the "poll" - its file descriptor to control the data in the availability. Whenever poll finds data in availability, this new data is printed.

However, what happens with this program? If the file that I want to track already contains data when the program starts, its contents are printed. This is normal. But later, when I edit the file using a text editor and save it, my program does not print new data.

So, how to control a regular file descriptor (and not a file by its path) for new data availability? Do I need to use a function other than poll ? Or am I missing the pollfd flag?

+4
source share
1 answer

You cannot use poll in regular files to view changes. However, there are several other ways. The classic approach is to call fstat at regular intervals with an open file descriptor and compare the returned fields with previous fields (in particular, st_size ). The modern approach is to use inotify(7) to monitor files. For example, recent GNU tail versions use this approach:

 $ strace tail -f /tmp/foobar ... open("/tmp/foobar", O_RDONLY) ) = 3 ... inotify_init() = 4 inotify_add_watch(4, "/tmp/foobar", IN_MODIFY|IN_ATTRIB|IN_DELETE_SELF|IN_MOVE_SELF) = 1 ... read(4, ... 

For more information on how this works, see the inotify (7) manual page.

+5
source

Source: https://habr.com/ru/post/1486475/


All Articles