inotify
是 Linux 内核提供的一种文件系统事件监控机制,它可以用来监控文件或目录的变化,如创建、删除、修改等。在 Debian 上使用 inotify
通常需要借助一些工具或库,比如 inotify-tools
或者编程接口 libinotify
。
以下是在 Debian 上使用 inotify
的基本步骤:
sudo apt update
inotify-tools
:sudo apt install inotify-tools
安装完成后,你可以使用 inotifywait
和 inotifywatch
这两个命令行工具。
inotifywait
可以用来监控文件或目录,并在检测到变化时执行命令。
例如,监控当前目录下的所有文件变化,并将事件输出到终端:
inotifywait -m .
参数说明:
-m
:监控模式,持续监控而不是等待事件。.
:监控当前目录。你可以添加更多的选项来定制监控行为,例如:
-e
:指定要监控的事件类型,如 create
, delete
, modify
等。--format
:自定义输出格式。--timefmt
:自定义时间格式。例如,监控当前目录下所有 .txt
文件的创建和修改事件:
inotifywait -m -e create,modify --format '%w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' *.txt
inotifywatch
用于统计文件系统事件,它会在指定的时间间隔内收集事件数据并输出报告。
例如,监控当前目录下的文件系统事件,并每 2 秒输出一次统计报告:
inotifywatch -t 2 -e create,delete,modify .
参数说明:
-t
:指定监控的总时间(秒)。-e
:指定要监控的事件类型。.
:监控当前目录。如果你需要在自己的程序中使用 inotify
,可以使用 libinotify
库。以下是一个简单的示例,展示如何在 C 程序中使用 libinotify
:
安装 libinotify-dev
:
sudo apt install libinotify-dev
编写 C 程序(例如 inotify_example.c
):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
int main() {
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return 1;
}
int wd = inotify_add_watch(fd, ".", IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return 1;
}
char buffer[4096];
while (1) {
int length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
perror("read");
break;
}
int i = 0;
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 += sizeof(struct inotify_event) + event->len;
}
}
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
编译程序:
gcc -o inotify_example inotify_example.c
运行程序:
./inotify_example
这个示例程序会监控当前目录下的文件创建、删除和修改事件,并在终端输出相关信息。
通过这些步骤,你可以在 Debian 上使用 inotify
来监控文件系统事件。