inotify 是 Linux 内核提供的一种文件系统事件监控机制,它可以实时监控文件或目录的变化,如创建、删除、修改等。在 Debian 上使用 inotify 通常需要借助一些工具或库,比如 inotify-tools 或者编程接口 libinotify。
以下是在 Debian 上使用 inotify 的基本步骤:
sudo apt update
inotify-tools:sudo apt install inotify-tools
安装完成后,你可以使用 inotifywait 和 inotifywatch 这两个命令行工具。
inotifywait 可以用来监控文件或目录,并在检测到变化时执行命令。
例如,监控当前目录下的所有文件变化,并将事件输出到终端:
inotifywait -m -r .
参数说明:
-m:监控模式,持续监控而不是只执行一次。-r:递归监控子目录。你可以添加更多的选项来定制监控行为,例如:
-e:指定要监控的事件类型,如 create, delete, modify 等。--format:自定义输出格式。例如,只监控创建和删除事件,并以 JSON 格式输出:
inotifywait -m -r -e create,delete --format '%w%f %e' .
inotifywatch 用于统计文件系统事件的发生次数。
例如,监控当前目录下 60 秒内的事件,并输出统计结果:
inotifywatch -t 60 -r .
参数说明:
-t:设置监控的总时间(秒)。-r:递归监控子目录。如果你需要在自己的程序中使用 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_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return 1;
}
char buffer[4096];
while (1) {
ssize_t 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 来监控文件系统的变化。