Created
March 26, 2020 18:47
-
-
Save LinArcX/4e48355041072f5be01ae9ef5afe9758 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define EVENT_SIZE (sizeof(struct inotify_event)) | |
| #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16)) | |
| int main() | |
| { | |
| int length, i = 0; | |
| int fd; | |
| int wd; | |
| char buffer[EVENT_BUF_LEN]; | |
| for (;;) { | |
| /*creating the INOTIFY instance*/ | |
| fd = inotify_init(); | |
| /*checking for error*/ | |
| if (fd < 0) { | |
| perror("inotify_init"); | |
| } | |
| /*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/ | |
| wd = inotify_add_watch(fd, "/home/linarcx/test.txt", IN_CREATE | IN_DELETE | IN_MODIFY | IN_CLOSE_WRITE); | |
| /*read to determine the event change happens on “/tmp” directory. Actually this read blocks until the change event occurs*/ | |
| length = read(fd, buffer, EVENT_BUF_LEN); | |
| /*checking for error*/ | |
| if (length < 0) { | |
| perror("read"); | |
| } | |
| /*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/ | |
| struct inotify_event* event = (struct inotify_event*)&buffer[i]; | |
| if (event->len) { | |
| if (event->mask & IN_CREATE) { | |
| if (event->mask & IN_ISDIR) { | |
| printf("New directory %s created.\n", event->name); | |
| } else { | |
| printf("New file %s created.\n", event->name); | |
| } | |
| } else if (event->mask & IN_DELETE) { | |
| if (event->mask & IN_ISDIR) { | |
| printf("Directory %s deleted.\n", event->name); | |
| } else { | |
| printf("File %s deleted.\n", event->name); | |
| } | |
| } else if (event->mask & IN_MODIFY) { | |
| if (event->mask & IN_ISDIR) { | |
| printf("Directory %s deleted.\n", event->name); | |
| } else { | |
| printf("File %s deleted.\n", event->name); | |
| } | |
| } else if (event->mask & IN_CLOSE_WRITE) { | |
| if (event->mask & IN_ISDIR) { | |
| printf("Directory %s deleted.\n", event->name); | |
| } else { | |
| printf("File %s deleted.\n", event->name); | |
| } | |
| } | |
| } | |
| //i += EVENT_SIZE + event->len; | |
| } | |
| /*removing the “/tmp” directory from the watch list.*/ | |
| inotify_rm_watch(fd, wd); | |
| /*closing the INOTIFY instance*/ | |
| close(fd); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment