温馨提示×

如何用inotify实现文件变更通知

小樊
39
2025-10-12 01:33:57
栏目: 编程语言

inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来检测文件的创建、修改、删除等操作。使用 inotify 可以实现高效的文件变更通知。以下是使用 inotify 的基本步骤:

1. 安装 inotify-tools

首先,你需要安装 inotify-tools,这是一个常用的命令行工具集,用于与 inotify 交互。

在 Debian/Ubuntu 系统上:

sudo apt-get install inotify-tools

在 CentOS/RHEL 系统上:

sudo yum install inotify-tools

2. 使用 inotifywait 监控文件或目录

inotifywaitinotify-tools 中的一个命令行工具,可以用来监控文件或目录的变化。

基本用法

inotifywait -m /path/to/directory

-m 选项表示监控模式,会持续监控指定目录的变化。

监控特定事件

你可以使用 -e 选项来指定要监控的事件类型,例如:

inotifywait -m -e create,modify,delete /path/to/directory

输出详细信息

你可以使用 -v 选项来输出更详细的信息:

inotifywait -m -v -e create,modify,delete /path/to/directory

处理事件

你可以将 inotifywait 的输出重定向到一个脚本中进行处理:

inotifywait -m -e create,modify,delete /path/to/directory | while read path action file; do
    echo "The file '$file' appeared in directory '$path' via '$action'"
done

3. 使用 inotify API 编程

如果你需要在程序中使用 inotify,可以使用 Linux 提供的 inotify API。以下是一个简单的 C 语言示例:

#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");
    }

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

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

        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);
                }
                if (event->mask & IN_DELETE) {
                    printf("File '%s' was deleted.\n", event->name);
                }
                if (event->mask & IN_MODIFY) {
                    printf("File '%s' was modified.\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除监控并关闭 inotify 实例
    inotify_rm_watch(fd, wd);
    close(fd);

    return 0;
}

总结

使用 inotify 可以高效地监控文件系统的变化。你可以通过命令行工具 inotifywait 快速实现文件变更通知,也可以通过编程接口 inotify API 在程序中实现更复杂的监控逻辑。

0