I am not understanding why the event->len
is return zero may be because the file name is not returned. but for only testing purpose you just comment it. And in second point
Your handling of i is broken, you never reset it to 0 in the loop. This causes any later inotify events to be considered only when they are longer than the longest event before them, which is not likely what you want.And please in while loop please put i += EVENT_SIZE + event->len;
int main() {
int notify_fd;
int length;
int i = 0;
char buffer[BUF_LEN];
notify_fd = inotify_init();
if (notify_fd < 0) {
perror("inotify_init");
}
int wd = inotify_add_watch(notify_fd, WATCH_FILE, IN_MODIFY | IN_ACCESS);
while(1)
{
length = read( notify_fd, buffer, BUF_LEN );
if ( length < 0 ) {
perror( "read" );
}
while ( i < length )
{
struct inotify_event *event =
(struct inotify_event *) &buffer[i];
// if (event->len) {
if (event->mask & IN_ACCESS) {
printf("The file %s was accessed.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("The file %s was modified.\n", event->name);
}
// }
i += EVENT_SIZE + event->len;
}
}
( void ) inotify_rm_watch( notify_fd, wd );
( void ) close( notify_fd);
exit( 0 );
}