This code works correctly:
#include <errno.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <string.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
int main(){
int length, i = 0, fd, wd1, wd2;
char buffer[EVENT_BUF_LEN];
fd = inotify_init();
wd1 = inotify_add_watch(fd, "/home/rjmacc/dirA", IN_MODIFY);
wd2 = inotify_add_watch(fd, "/home/rjmacc/dirB", IN_MODIFY);
while(true)
{
printf("calling read function\n");
i = 0;
length = read(fd, buffer, EVENT_BUF_LEN );
while(i < length){
printf("length read = %d\n", length);
struct inotify_event *event = ( struct inotify_event *)&buffer[i];
if(event->len){
printf ("event:\n");
printf ("\t wd: %d\n", event->wd);
printf ("\t mask: %d\n", event->mask);
printf ("\tcookie: %d\n", event->cookie);
printf ("\t len: %d\n", event->len);
printf ("\t name: %s\n", event->name);
if(event->mask & IN_MODIFY){
if(event->wd == wd1){
printf("Pathname1 file '%s' modified.\n",event->name);
}
if(event->wd == wd2){
printf("Pathname2 file '%s' modified.\n",event->name);
}
}
}
i += EVENT_SIZE + event->len;
}
}
inotify_rm_watch(fd, wd1);
inotify_rm_watch(fd, wd2);
close(fd);
}
In the cases where more than one event is seen, that is caused by the actions occurring in the directory. Some actions (e.g. using vi) will cause more than one event to occur in the directory, as reflected in the pathname that is returned from the watcher.