Using read with inotify

后端 未结 1 1918
鱼传尺愫
鱼传尺愫 2021-02-13 04:01

I have been studying inotify call, but I still a bit flaky when it comes to the read interface. These are the most relevant resourses I could find regarding how to properly inte

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 04:26

    Basic usage

    According to inotify(7), you can use the FIONREAD ioctl to find out how much data is available to be read and size your buffer accordingly. Here's some (very rough) code that can accomplish this:

    unsigned int avail;
    ioctl(inotify_fd, FIONREAD, &avail);
    
    char buffer[avail];
    read(fd, buffer, avail);
    
    int offset = 0;
    while (offset < avail) {
        struct inotify_event *event = (inotify_event*)(buffer + offset);
    
        // Insert logic here
        my_process_inotify_event(event);
    
        offset = offset + sizeof(inotify_event) + event->len;
    }
    

    More robust usage

    inotify-tools provides a higher-level interface to inotify. You can use it instead of accessing inotify, or you can see how it implements inotifytools_next_events to safely and robustly read all available events.

    Partial events and truncation

    In response to your questions about truncation, I do not think that the kernel will ever return a partial inotify_event or truncate an inotify_event if the buffer given is too small for all events. The following paragraph from the inotify(7) manpage suggests this:

    The behavior when the buffer given to read(2) is too small to return information about the next event depends on the kernel version: in kernels before 2.6.21, read(2) returns 0; since kernel 2.6.21, read(2) fails with the error EINVAL.

    As do the following comments from inotifytools.c:

    // oh... no.  this can't be happening.  An incomplete event.
    // Copy what we currently have into first element, call self to
    // read remainder.
    // oh, and they BETTER NOT overlap.
    // Boy I hope this code works.
    // But I think this can never happen due to how inotify is written.
    

    0 讨论(0)
提交回复
热议问题