inotify 是 Linux 系统中用于监控文件系统事件的一种机制。通过 inotify,你可以实时监控文件或目录的变化,如创建、删除、修改等。以下是如何使用 inotify 进行文件变化检测的步骤:
首先,你需要安装 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 是 inotify-tools 中的一个命令行工具,用于等待并报告文件系统事件。
inotifywait [选项] 目录
例如,监控当前目录下的所有文件变化:
inotifywait -m .
-m:监控模式,持续监控文件系统事件。-r:递归监控子目录。-e:指定要监控的事件类型,如 create、delete、modify、move 等。-q:安静模式,只输出事件信息,不显示其他信息。--format:自定义输出格式。监控当前目录及其子目录下的所有 .txt 文件的创建、修改和删除事件:
inotifywait -m -r -e create,modify,delete --format '%w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' .
inotifywatch 是另一个 inotify-tools 中的命令行工具,用于统计文件系统事件。
inotifywatch [选项] 目录
例如,监控当前目录下的所有文件变化,并输出统计信息:
inotifywatch -m -r -e create,modify,delete .
-m:监控模式,持续监控文件系统事件。-r:递归监控子目录。-e:指定要监控的事件类型,如 create、modify、delete、move 等。--timefmt:自定义时间格式。监控当前目录及其子目录下的所有 .txt 文件的创建、修改和删除事件,并输出统计信息:
inotifywatch -m -r -e create,modify,delete --timefmt '%Y-%m-%d %H:%M:%S' .
除了命令行工具外,inotify 还提供了编程接口,可以在 C/C++ 程序中使用。你可以使用 libinotify 库来编写自定义的文件变化检测程序。
#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 进行文件变化检测,无论是通过命令行工具还是编程接口。