inotify是Linux内核提供的文件系统事件监控机制,自2.6.13版本引入,通过inotify_init()创建实例,inotify_add_watch()添加监控路径,读取文件描述符获取事件,支持IN_CREATE、IN_DELETE等事件类型,相比轮询更高效,广泛用于文件同步、日志监控等场景。

Linux 提供了 inotify 机制,用于实时监控文件系统事件,比如文件的创建、修改、删除等。它比轮询方式高效得多,是开发文件同步工具、日志监控、自动构建系统等功能的核心技术。
inotify 是 Linux 内核从 2.6.13 版本开始引入的一个子系统,允许应用程序监听目录或文件的各种事件。相比旧的 dnotify,它支持更细粒度的控制,并且使用文件描述符接口,易于集成到事件循环中。
常见可监控的事件包括:
通过系统调用操作 inotify,主要步骤如下:
下面是一个监控当前目录下文件创建和删除的简单程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/inotify.h>
#define BUF_LEN 1024
int main() {
int fd, wd;
char buffer[BUF_LEN];
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
wd = inotify_add_watch(fd, ".", IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
printf("Monitoring current directory...\n");
while (1) {
int len = read(fd, buffer, BUF_LEN);
if (len < 0) {
perror("read");
continue;
}
for (int i = 0; i < len; ) {
struct inotify_event *event = (struct inotify_event *)&buffer[i];
if (event->mask & IN_CREATE) {
printf("Created: %s\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("Deleted: %s\n", event->name);
}
i += sizeof(struct inotify_event) + event->len;
}
}
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
编译运行:
gcc monitor.c -o monitor && ./monitor
在另一个终端创建或删除文件,即可看到输出。
实际使用中需要注意以下几点:
对于脚本开发,也可以使用命令行工具 inotifywait(来自 inotify-tools 包)快速测试:
inotifywait -m /path/to/dir -e create,delete,modify
基本上就这些。inotify 轻量、高效,适合大多数本地文件监控场景。理解其机制后,可以轻松集成进守护进程或自动化系统中。
以上就是Linux 开发:如何监控文件系统事件 (inotify)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号