温馨提示×

linux fsnotify如何进行事件过滤

小樊
83
2025-01-01 22:04:09
栏目: 智能运维
Linux服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

fsnotify 是一个用于监控文件系统事件的库,它允许应用程序在文件或目录发生更改时接收通知

  1. 使用 fsnotify_add_watch 函数添加监控:

    在添加监控之前,你需要指定要监控的目录和感兴趣的事件类型。例如,要监控 /home/user 目录下的所有文件和子目录中的 CREATEDELETE 事件,你可以这样做:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/inotify.h>
    #include <unistd.h>
    
    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;
    }
    
  2. 使用 inotify_event 结构体过滤事件:

    inotify_event 结构体包含了事件的详细信息,如文件名、事件类型等。你可以通过检查这些信息来过滤你感兴趣的事件。例如,要过滤 /home/user 目录下的所有 CREATE 事件,你可以这样做:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/inotify.h>
    #include <unistd.h>
    
    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 事件。你可以根据需要修改条件来过滤其他事件类型。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:linux fsnotify如何避免误报情况

0