Reputation: 69
I am trying to get notifications using inotify_add-watch() for a file when it is modified (inotify_add_watch (fd, filename.c_str(), IN_MODIFY);) on linux file system(linux kernel 4.9.0).
But after notification, read() is expected to call twice until I get notification for the next modification on the file /etc/temp. Can someone clarify why do I need to call read() twice? Thank you.
int fd, wd;
fd = inotify_init ();
if (fd < 0)
{
perror ("inotify_init () = ");
}
else
{
std::string filename = "/etc/test";
wd = inotify_add_watch (fd, filename.c_str(), IN_MODIFY);
if (wd < 0)
{
perror ("inotify_add_watch");
}
else
{
char* buffer = new char[1024];
while(true)
{
//first read blocks until the /etc/temp file is modified,
//it returns 16 which is sizeof(struct inotify_event)
printf("first read %d), read( fd, buffer, 1024));
//second read() does not block and read returns 16 again
printf("second read %d), read( fd, buffer, 1024));
}
}
}
Upvotes: 0
Views: 856
Reputation: 123400
You have to consume all pending events before it'll start blocking again.
When you e.g. do echo foo > /etc/test
, you may get two events: one for the truncation, and one for the write.
If you don't consume both, the next will be returned immediately.
Upvotes: 2