fsnotify
是一个用于监控文件系统事件的库,它允许应用程序在文件或目录发生更改时接收通知
-
使用
fsnotify_add_watch
函数添加监控:在添加监控之前,你需要指定要监控的目录和感兴趣的事件类型。例如,要监控
/home/user
目录下的所有文件和子目录中的CREATE
和DELETE
事件,你可以这样做:#include
#include #include #include #include int main() { int length, i = 0; int fd = inotify_init(); if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); } int wd = inotify_add_watch(fd, "/home/user", IN_MODIFY | IN_CREATE | IN_DELETE); if (wd < 0) { perror("inotify_add_watch"); close(fd); exit(EXIT_FAILURE); } char buffer[1024]; length = read(fd, buffer, sizeof(buffer) - 1); if (length < 0) { perror("read"); inotify_rm_watch(fd, wd); close(fd); exit(EXIT_FAILURE); } buffer[length] = '\0'; printf("Event: %s\n", buffer); inotify_rm_watch(fd, wd); close(fd); return 0; } -
使用
inotify_event
结构体过滤事件:inotify_event
结构体包含了事件的详细信息,如文件名、事件类型等。你可以通过检查这些信息来过滤你感兴趣的事件。例如,要过滤/home/user
目录下的所有CREATE
事件,你可以这样做:#include
#include #include #include #include int main() { int length, i = 0; int fd = inotify_init(); if (fd < 0) { perror("inotify_init"); exit(EXIT_FAILURE); } int wd = inotify_add_watch(fd, "/home/user", IN_CREATE); if (wd < 0) { perror("inotify_add_watch"); close(fd); exit(EXIT_FAILURE); } char buffer[1024]; while (1) { length = read(fd, buffer, sizeof(buffer) - 1); if (length < 0) { perror("read"); inotify_rm_watch(fd, wd); close(fd); exit(EXIT_FAILURE); } buffer[length] = '\0'; struct inotify_event *event = (struct inotify_event *)&buffer[i]; if (event->mask & IN_CREATE) { printf("Create event detected: %s\n", event->name); } i += length + 1; // Skip the length and null terminator } inotify_rm_watch(fd, wd); close(fd); return 0; } 在这个例子中,我们只检查
event->mask & IN_CREATE
是否为真,如果是,则表示检测到了CREATE
事件。你可以根据需要修改条件来过滤其他事件类型。