How to use inotify in C?

I was looking for inotify related questions, and this is a bit different ...

I use the following code to monitor changes to a single file (not a directory). When testing read () returns when I save the target file, which means that it works. But event-> mask is 32768, which is not IN_MODIFY, and the name is empty. Another problem: he cannot keep track of. When I change the file a second time, it does not respond. Thanks for the help!

#include <sys/inotify.h> #include <unistd.h> #include <stdio.h> #define EVENT_SIZE (sizeof (struct inotify_event)) #define BUF_LEN (16 * (EVENT_SIZE + 16)) int main() { int fd; fd = inotify_init(); if (fd < 0) perror("inotify_init()"); int wd; wd = inotify_add_watch(fd, "target.txt", IN_MODIFY); if (wd < 0) perror("inotify_add_watch"); char buf[BUF_LEN]; int len; start: len = read(fd, buf, BUF_LEN); if (len > 0) { int i = 0; while (i < len) { struct inotify_event *event; event = (struct inotify_event *) &buf[i]; printf("wd=%d mask=%x cookie=%u len=%u\n", event->wd, event->mask, event->cookie, event->len); if (event->mask & IN_MODIFY) printf("file modified %s", event->name); if (event->len) printf("name=%s\n", event->name); i += EVENT_SIZE + event->len; } } goto start; return 0; } 
+4
source share
2 answers

0x8000 corresponds to IN_IGNORED . Its presence in the mask indicates that the inotify clock was deleted because the file was deleted. Your editor probably deleted the old file and put the new file in its place. Changing the file a second time did not affect the clock being deleted.

The name is not returned because you are not looking at the directory.

On the inotify page.

The name field is present only when the event is returned for the file inside the observed directory; it identifies the file path relative to the observed directory.

...

IN_IGNORED - The watch was deleted explicitly (inotify_rm_watch (2)) or automatically (the file was deleted or the file system was unmounted).

+5
source

event-> mask 32768 is equivalent to 0x8000, which is IN_IGNORED For more information: "/usr/include/linux/inotify.h"

  if (event->mask & IN_IGNORED) { /*Remove watch*/ inotify_rm_watch(fileDescriptor,watchDescriptor) /*Add watch again*/ inotify_add_watch } 
+3
source

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


All Articles