I wrote this little example program just to start using inotify. The program adds a watch on a file, looking for the event of closing the file after having opened it for writing. When the even fires, I remove the watch, write something different on the file which the event was fired for and then I add again the watch on the same event on that file. All this in a cycle. The problem is that when I do any kind of writes on the file, even simple ones like this "echo 0 > file_watched", the watching program receives an unending series of events. What am I doing wrong?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <sys/inotify.h>
#define FILE_CONTENTS "\
irrelevant contents\n"
#define EVENT_SIZE (sizeof(struct inotify_event))
int main(int argc, char **argv)
{
if (argc < 2) {
printf("not enough arguments.\n");
exit(1);
}
char event[EVENT_SIZE];
int wd;
char *path_name = argv[1];
int ifd = inotify_init();
if (ifd == -1) {
printf("inotify_init() problem.\n");
exit(1);
}
while (true) {
wd = inotify_add_watch(ifd, path_name, IN_CLOSE_WRITE);
if (wd == -1) {
printf("inotify_add_watch() problem.\n");
exit(1);
}
if (read(ifd, event, EVENT_SIZE) != EVENT_SIZE) {
printf("read() problem.\n");
exit(1);
}
if(inotify_rm_watch(ifd, wd) == -1) {
perror("inotify_rm_watch()");
exit(1);
}
printf("%s modified. now working on it\n", path_name);
fflush(stdout);
FILE *file = fopen(path_name, "w");
fprintf(file, "%s", FILE_CONTENTS);
fflush(file);
fclose(file);
printf("%s restored\n", path_name);
fflush(stdout);
}
return (EXIT_SUCCESS);
}