4

Program:

#include <stdio.h>
#include <sys/inotify.h>

int main()
{
    int fd = inotify_init();
    int wd1 = inotify_add_watch(fd, "/home/guest/a", IN_MODIFY);
    struct inotify_event *event = (struct inotify_event*) malloc(sizeof(struct inotify_event));
    read(fd, event, 1000);
    if (event->mask & IN_MODIFY) {
        printf("File '%s' is modified\n", event->name);
    }
}

Output:

$ ./a.out 
File '' is modified
$

I expected that the above program will notify with the filename if file a is modified. But it notify without filename. So, how to get the filename if the file is modified using inotify.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
mohangraj
  • 9,842
  • 19
  • 59
  • 94
  • 3
    [Do not cast the return value of `malloc()`, and `void *` in c in general](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). And you really don't need to `malloc()` anything at all. Just `struct inotify_event event; read(fd, &event, sizeof(event))`. will do – Iharob Al Asimi Dec 22 '15 at 14:55
  • 2
    Check the return value of `read()`. – John Zwinck Dec 22 '15 at 14:57

1 Answers1

4

The documentation says:

The name field is present only when an event is returned for a file inside a watched directory; it identifies the file pathname relative to the watched directory. This pathname is null-terminated, and may include further null bytes ('\0') to align subsequent reads to a suitable address boundary.

So your problem is that you're expecting inotify to "echo" the name back to you, but that is not how it works.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Is there any way to achieve that? – mohangraj Dec 22 '15 at 15:00
  • 1
    Yes, you can keep your own mapping of watch descriptors to filenames. This has been discussed a bit here: http://stackoverflow.com/a/9313324/4323 – John Zwinck Dec 22 '15 at 15:02
  • It is the only way to get the filename. But this scenario will also fail in some condition like if more than one file is added to fd passed to notify_add_watch function. – mohangraj Dec 22 '15 at 15:12
  • @mrg: No. Every time you add a watch, you get a new watch descriptor. There is therefore a mapping from watch descriptors to watches, and one watch on one file has a filename. – John Zwinck Dec 22 '15 at 15:16
  • 1
    @iharob: There is no "watched directory" in the OP's case: the code watches `/home/guest/a` and the OP says that `a` is a file. No directory is watched. Therefore no names are reported. Because they are meant to be inferred from the watch descriptor. – John Zwinck Dec 22 '15 at 16:24
  • That clears things up. It doesn't make sense to return the name of the watched "*file*" because you know the name or else, how did you start watchng it in the first place? I Appologize, let me remove the comments. – Iharob Al Asimi Dec 23 '15 at 17:13