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

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

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys>
#include <limits.h>
int main() {
int fd = inotify_init();
if (fd <h2>如何从缓冲区读取并解析具体的变更事件</h2>
<p>添加监听后,程序需要通过 <code>read()</code> 系统调用从文件描述符中读取数据。由于 <code>inotify</code> 可能同时产生多个事件,单次 <code>read()</code> 调用可能返回包含多个 <code>struct inotify_event</code> 结构体的连续内存块。因此,必须编写循环逻辑,根据每次读取的字节数 <code>nbytes</code>,逐个解析结构体。每个事件结构体包含 <code>wd</code>(监听描述符)、<code>mask</code>(事件类型)、<code>cookie</code>(用于关联成对事件)和 <code>name</code>(文件名,仅当事件针对目录内某项时有效)。解析时需检查 <code>mask</code> 位标志以确定具体发生了何种操作,例如判断是否包含 <code>IN_ISDIR</code> 来区分文件与目录变更。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill14075" title="Linux 系统管理"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="Linux 系统管理" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill14075" title="Linux 系统管理" class="overflowclass">Linux 系统管理</a>
<p class="overflowclass">Linux 系统管理技能。避免权限陷阱、静默失败和常见运维错误,覆盖用户权限、文件系统、进程管理、网络配置等日常运维场景。触发词:Linux 管理、系统运维、权限、Shell 命令。</p>
</div>
<a rel="nofollow" href="/xiazai/skill14075" title="Linux 系统管理" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p><img src="https://img.php.cn/upload/article/001/242/473/179557844327515.png?x-oss-process=image/resize,p_40" alt="Linux 目录怎么用 inotify 监控文件变化"></p>
<pre class="brush:php;toolbar:false;">#include <sys>
#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 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;
}
}</string.h></stdio.h></sys>
如何处理递归监控深层子目录的变化
默认情况下,inotify_add_watch() 仅监控指定路径本身或其直接子项的顶层事件,不会自动深入子目录树。若需监控整个目录树的所有层级变化,必须在代码中维护一个映射表,记录每个子目录对应的 watch descriptor。当解析到 IN_ISDIR 且为 IN_CREATE 事件时,程序应动态调用 inotify_add_watch() 对新创建的子目录进行追加监听。反之,若检测到 IN_DELETE_SELF 或 IN_IGNORED 事件,则需从映射表中移除该描述符并关闭相关资源,以防止文件描述符泄漏。这种手动递归管理确保了监控范围覆盖所有嵌套层级。










