linux

inotify在Linux系统中如何工作

小樊
44
2025-11-16 19:17:08
栏目: 智能运维

inotify 是 Linux 内核提供的一种文件系统事件监控机制,它允许应用程序实时监控文件或目录的变化,如创建、删除、修改等。inotify 的工作原理主要依赖于内核与用户空间之间的通信,以下是其详细的工作流程:

1. 初始化 inotify 实例

2. 添加监控

3. 事件通知

4. 读取事件

5. 处理事件

6. 移除监控

关键点总结

示例代码

以下是一个简单的示例代码,展示了如何使用 inotify 监控一个目录的变化:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>

#define EVENT_SIZE  ( sizeof (struct inotify_event) )
#define BUF_LEN     ( 1024 * ( EVENT_SIZE + 16 ) )

int main(int argc, char **argv) {
    int length, i = 0;
    int fd;
    int wd;
    char buffer[BUF_LEN];

    // 创建 inotify 实例
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        return 1;
    }

    // 添加监控
    wd = inotify_add_watch(fd, "/path/to/directory", IN_CREATE | IN_DELETE | IN_MODIFY);
    if (wd < 0) {
        perror("inotify_add_watch");
        close(fd);
        return 1;
    }

    // 读取事件
    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
            break;
        }

        while (i < length) {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->len) {
                if (event->mask & IN_CREATE) {
                    printf("File %s was created.\n", event->name);
                } else if (event->mask & IN_DELETE) {
                    printf("File %s was deleted.\n", event->name);
                } else if (event->mask & IN_MODIFY) {
                    printf("File %s was modified.\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除监控并关闭文件描述符
    inotify_rm_watch(fd, wd);
    close(fd);

    return 0;
}

这个示例代码展示了如何初始化 inotify 实例、添加监控、读取事件以及处理事件。通过这种方式,应用程序可以实时监控指定目录的变化。

0
看了该问题的人还看了