linux

如何使用inotify进行文件变化检测

小樊
46
2025-08-03 10:02:00
栏目: 编程语言

inotify 是 Linux 系统中用于监控文件系统事件的一种机制。通过 inotify,你可以实时监控文件或目录的变化,如创建、删除、修改等。以下是如何使用 inotify 进行文件变化检测的步骤:

安装 inotify-tools

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

在 Debian/Ubuntu 系统上,可以使用以下命令安装:

sudo apt-get update
sudo apt-get install inotify-tools

在 CentOS/RHEL 系统上,可以使用以下命令安装:

sudo yum install epel-release
sudo yum install inotify-tools

使用 inotifywait 监控文件或目录

inotifywaitinotify-tools 中的一个命令行工具,用于等待并报告文件系统事件。

基本用法

inotifywait [选项] 目录

例如,监控当前目录下的所有文件变化:

inotifywait -m .

常用选项

示例

监控当前目录及其子目录下的所有 .txt 文件的创建、修改和删除事件:

inotifywait -m -r -e create,modify,delete --format '%w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' .

使用 inotifywatch 监控文件或目录

inotifywatch 是另一个 inotify-tools 中的命令行工具,用于统计文件系统事件。

基本用法

inotifywatch [选项] 目录

例如,监控当前目录下的所有文件变化,并输出统计信息:

inotifywatch -m -r -e create,modify,delete .

常用选项

示例

监控当前目录及其子目录下的所有 .txt 文件的创建、修改和删除事件,并输出统计信息:

inotifywatch -m -r -e create,modify,delete --timefmt '%Y-%m-%d %H:%M:%S' .

编程接口

除了命令行工具外,inotify 还提供了编程接口,可以在 C/C++ 程序中使用。你可以使用 libinotify 库来编写自定义的文件变化检测程序。

示例代码(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];

    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
    }

    wd = inotify_add_watch(fd, ".", IN_CREATE | IN_DELETE | IN_MODIFY);
    if (wd < 0) {
        perror("inotify_add_watch");
    }

    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 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;
    }

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

    return 0;
}

编译并运行该程序:

gcc -o inotify_example inotify_example.c
./inotify_example

通过以上方法,你可以使用 inotify 进行文件变化检测,无论是通过命令行工具还是编程接口。

0
看了该问题的人还看了