使用 inotify 监控 linux 目录变化,核心做法是调用 inotify_init() 创建文件描述符,通过 inotify_add_watch() 向目标路径注册监听事件(如 in_modify、in_create),并在循环中读取 /dev/inotify 的数据流以获取具体变更详情。该机制基于内核态实现,相比轮询文件系统能显著降低 cpu 开销并提高响应速度。

如何初始化并添加对特定目录的监听
初始化监听的第一步是创建 inotify 实例并绑定到具体路径。开发者需要包含 <sys></sys> 头文件,调用 inotify_init() 获取一个非负的文件描述符。随后,必须调用 inotify_add_watch() 函数,传入该描述符、目标目录路径以及感兴趣的事件掩码。如果目录不存在或权限不足,该调用会返回 -1 并设置 errno。成功添加后,系统内核会在该目录发生指定事件时,将数据写入对应的文件描述符缓冲区。

Linux 系统管理技能。避免权限陷阱、静默失败和常见运维错误,覆盖用户权限、文件系统、进程管理、网络配置等日常运维场景。触发词:Linux 管理、系统运维、权限、Shell 命令。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <limits.h>
int main() {
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init failed");
return 1;
}
// 监控当前目录下的创建和修改事件
int wd = inotify_add_watch(fd, ".", IN_CREATE | IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch failed");
close(fd);
return 1;
}
printf("Watching directory with watch descriptor: %d\n", wd);
// 后续需配合 read() 循环处理事件
close(fd);
return 0;
}如何从缓冲区读取并解析具体的变更事件
添加监听后,程序需要通过 read() 系统调用从文件描述符中读取数据。由于 inotify 可能同时产生多个事件,单次 read() 调用可能返回包含多个 struct inotify_event 结构体的连续内存块。因此,必须编写循环逻辑,根据每次读取的字节数 nbytes,逐个解析结构体。每个事件结构体包含 wd(监听描述符)、mask(事件类型)、cookie(用于关联成对事件)和 name(文件名,仅当事件针对目录内某项时有效)。解析时需检查 mask 位标志以确定具体发生了何种操作,例如判断是否包含 IN_ISDIR 来区分文件与目录变更。

#include <sys/inotify.h>
#include <stdio.h>
#include <string.h>
void process_events(int fd, int wd) {
char buffer[4096];
ssize_t nbytes = read(fd, buffer, sizeof(buffer));
if (nbytes < 0) {
perror("read failed");
return;
}
// 遍历缓冲区中的所有事件
for (char *ptr = buffer; ptr < buffer + nbytes; ) {
struct inotify_event *event = (struct inotify_event *) ptr;
if (event->mask & IN_CREATE) {
printf("Created: %s\n", event->name ? event->name : "(root)");
} else if (event->mask & IN_MODIFY) {
printf("Modified: %s\n", event->name ? event->name : "(root)");
}
// 移动指针到下一个事件
ptr += sizeof(struct inotify_event) + event->len;
}
}如何处理递归监控深层子目录的变化
默认情况下,inotify_add_watch() 仅监控指定路径本身或其直接子项的顶层事件,不会自动深入子目录树。若需监控整个目录树的所有层级变化,必须在代码中维护一个映射表,记录每个子目录对应的 watch descriptor。当解析到 IN_ISDIR 且为 IN_CREATE 事件时,程序应动态调用 inotify_add_watch() 对新创建的子目录进行追加监听。反之,若检测到 IN_DELETE_SELF 或 IN_IGNORED 事件,则需从映射表中移除该描述符并关闭相关资源,以防止文件描述符泄漏。这种手动递归管理确保了监控范围覆盖所有嵌套层级。

















