inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以实时监控文件或目录的变化,如创建、删除、修改等。要监控 inotify 的事件队列,可以使用 inotifywait 命令行工具或编写自己的程序来使用 inotify API。以下是两种方法的详细说明:
inotifywait 命令行工具inotifywait 是 inotify-tools 包的一部分,可以方便地监控文件系统事件。以下是一个简单的示例:
安装 inotify-tools:
sudo apt-get install inotify-tools # Debian/Ubuntu
sudo yum install inotify-tools # CentOS/RHEL
sudo dnf install inotify-tools # Fedora
监控目录:
inotifywait -m /path/to/directory -e create,delete,modify
这条命令会持续监控 /path/to/directory 目录,并在有创建、删除或修改事件发生时输出相关信息。
inotify API如果你需要更复杂的监控逻辑,可以编写自己的程序来使用 inotify API。以下是一个简单的 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];
// 检查命令行参数
if (argc != 2) {
printf("Usage: %s <path-to-watch>\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_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
// 读取事件
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);
}
if (event->mask & IN_DELETE) {
printf("File %s deleted\n", event->name);
}
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);
}
编译并运行这个程序:
gcc -o inotify_monitor inotify_monitor.c
./inotify_monitor /path/to/directory
这个程序会持续监控指定的目录,并在有文件创建、删除或修改时输出相关信息。
inotifywait 命令行工具可以快速实现基本的文件系统事件监控。inotify API 可以实现更复杂的监控逻辑和自定义处理。选择哪种方法取决于你的具体需求和使用场景。