linux

Linux inotify如何监控文件变化

小樊
92
2025-02-17 14:07:12
栏目: 智能运维

在Linux中,inotify是一个用于监控文件系统事件的接口。它允许应用程序实时地获取有关文件或目录的变化信息,例如文件的创建、删除、修改等。要使用inotify监控文件变化,你需要使用Linux内核提供的inotify API。

以下是使用inotify监控文件变化的基本步骤:

  1. 包含必要的头文件

    #include <sys/inotify.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    
  2. 初始化inotify实例: 使用inotify_init()函数创建一个inotify实例,并返回一个文件描述符。

    int fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        exit(EXIT_FAILURE);
    }
    
  3. 添加监控: 使用inotify_add_watch()函数将需要监控的文件或目录添加到inotify实例中。该函数返回一个监控描述符(watch descriptor),用于后续操作。

    int wd = inotify_add_watch(fd, "/path/to/file_or_directory", IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        close(fd);
        exit(EXIT_FAILURE);
    }
    
  4. 读取事件: 使用read()函数从inotify实例的文件描述符中读取事件。每个事件都包含一个或多个标志,指示发生了哪种类型的文件变化。

    char buffer[4096];
    ssize_t length = read(fd, buffer, sizeof(buffer));
    if (length < 0) {
        perror("read");
        close(fd);
        exit(EXIT_FAILURE);
    }
    
    // 解析事件
    char *ptr = buffer;
    while (ptr < buffer + length) {
        struct inotify_event *event = (struct inotify_event *)ptr;
        if (event->len) {
            if (event->mask & IN_MODIFY) {
                printf("File modified: %s\n", event->name);
            }
            if (event->mask & IN_CREATE) {
                printf("File created: %s\n", event->name);
            }
            if (event->mask & IN_DELETE) {
                printf("File deleted: %s\n", event->name);
            }
        }
        ptr += sizeof(struct inotify_event) + event->len;
    }
    
  5. 清理资源: 当不再需要监控时,使用inotify_rm_watch()函数移除监控,并关闭inotify实例的文件描述符。

    inotify_rm_watch(fd, wd);
    close(fd);
    

请注意,上述代码示例仅用于演示目的,实际应用中可能需要处理更多的错误情况和边界条件。此外,inotify API提供了许多其他功能和选项,可以根据需要进行配置和使用。

0
看了该问题的人还看了