温馨提示×

如何使用inotify实现文件监控

小樊
42
2025-09-10 17:20:10
栏目: 编程语言

inotify 是 Linux 系统提供的一种文件系统事件监控机制,它可以实时监控文件或目录的变化,如创建、删除、修改等。以下是使用 inotify 实现文件监控的基本步骤:

1. 安装必要的库

在大多数 Linux 发行版中,inotify 已经是内核的一部分,但你可能需要安装相关的开发库。例如,在 Debian/Ubuntu 系统上,你可以使用以下命令安装:

sudo apt-get install libinotify-dev

2. 编写代码

以下是一个简单的 C 语言示例,演示如何使用 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];

    // 检查命令行参数
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

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

    // 添加监控目录
    wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        exit(EXIT_FAILURE);
    }

    printf("Monitoring directory: %s\n", argv[1]);

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

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

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

    exit(EXIT_SUCCESS);
}

3. 编译代码

使用 gcc 编译上述代码:

gcc -o inotify_example inotify_example.c -linotify

4. 运行程序

运行编译后的程序,并指定要监控的目录:

./inotify_example /path/to/directory

解释

  • inotify_init():创建一个新的 inotify 实例。
  • inotify_add_watch():添加一个监控项,指定要监控的文件或目录以及感兴趣的事件类型(如 IN_MODIFYIN_CREATEIN_DELETE)。
  • read():从 inotify 实例读取事件。
  • inotify_rm_watch():移除一个监控项。
  • close():关闭 inotify 实例。

通过这种方式,你可以实现对文件系统的实时监控,并根据需要处理不同的事件。

0