inotify 是 Linux 内核提供的一种文件系统事件监控机制,它可以用来监控文件或目录的变化,如创建、删除、修改等。inotify API 允许应用程序实时接收这些事件通知。
以下是使用 inotify API 的基本步骤:
初始化 inotify 实例:
使用 inotify_init() 函数创建一个新的 inotify 实例。
int fd = inotify_init();
if (fd < 0) {
// 错误处理
}
添加监控:
使用 inotify_add_watch() 函数来添加一个或多个文件或目录的监控。
int wd = inotify_add_watch(fd, "/path/to/file_or_directory", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
// 错误处理
}
这里的 IN_MODIFY、IN_CREATE 和 IN_DELETE 是事件掩码,指定了你想要监控的事件类型。
读取事件:
使用 read() 函数从 inotify 文件描述符中读取事件。
char buffer[4096];
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
// 错误处理
}
// 解析 buffer 中的事件
buffer 将包含一个或多个 inotify_event 结构体,你需要解析这个结构体来获取事件的详细信息。
处理事件: 根据解析出的事件类型和文件名,执行相应的操作。
移除监控:
当不再需要监控时,使用 inotify_rm_watch() 函数移除监控。
inotify_rm_watch(fd, wd);
关闭 inotify 实例:
最后,使用 close() 函数关闭 inotify 文件描述符。
close(fd);
下面是一个简单的示例,演示了如何使用 inotify API 监控一个文件的变化:
#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 <file_or_directory>\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_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_MODIFY) {
printf("File %s was modified\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除监控并关闭 inotify 实例(这里永远不会执行到)
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
请注意,这个示例程序会无限循环地监控指定的文件或目录,并在文件被修改时打印一条消息。在实际应用中,你可能需要添加逻辑来优雅地退出循环和处理其他类型的事件。