linuxinotify

Why is it required to call read() twice with inotify_add_watch()


I am trying to get notifications using inotify_add-watch() for a file when it is modified using inotify_add_watch (fd, filename.c_str(), IN_MODIFY); on Linux file system (Linux kernel 4.9.0).

But after notification, read() needs to be called twice until I get notification for the next modification on the file /etc/temp. Can someone clarify why I need to call read() twice?

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));
         }
     }
}

Solution

  • 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.