安装工具包
inotify-tools
(命令行工具,非API,用于快速测试):sudo apt-get update && sudo apt-get install inotify-tools
inotify
内核模块(现代Ubuntu默认支持):lsmod | grep inotify # 检查模块是否加载
关键系统参数
cat /proc/sys/fs/inotify/max_user_watches # 单用户最大监控项数
cat /proc/sys/fs/inotify/max_user_instances # 单用户最大实例数
sudo sysctl -w fs.inotify.max_user_watches=524288
永久生效需修改 /etc/sysctl.conf
并执行 sysctl -p
。创建inotify实例
#include <sys/inotify.h>
int fd = inotify_init();
if (fd < 0) { perror("inotify_init failed"); exit(1); }
添加监控路径
// 监控目录(递归需手动处理子目录)
int wd = inotify_add_watch(fd, "/path/to/directory",
IN_CREATE | IN_MODIFY | IN_DELETE);
if (wd < 0) { perror("inotify_add_watch failed"); exit(1); }
// 事件类型说明:
// IN_CREATE:文件/目录创建
// IN_MODIFY:文件内容修改
// IN_DELETE:文件/目录删除
// 更多事件类型见
读取事件
char buffer[1024];
ssize_t len = read(fd, buffer, sizeof(buffer));
if (len < 0) { perror("read failed"); exit(1); }
// 解析事件
struct inotify_event *event;
for (char *p = buffer; p < buffer + len; ) {
event = (struct inotify_event *)p;
if (event->len) {
printf("Event: %s, File: %s\n",
(event->mask & IN_CREATE) ? "CREATE" : "MODIFY/DELETE",
event->name);
}
p += sizeof(struct inotify_event) + event->len;
}
清理资源
inotify_rm_watch(fd, wd); // 移除监控
close(fd); // 关闭实例
Python(使用inotify
库)
import inotify.adapters
notifier = inotify.adapters.Inotify()
notifier.add_watch('/path/to/directory',
mask=inotify.constants.IN_CREATE |
inotify.constants.IN_MODIFY |
inotify.constants.IN_DELETE)
for event in notifier.event_gen():
if event is not None:
print(f"Event: {event[1].maskname}, File: {event[2]}")
inotify-tools
的--recursive
选项或库的特定方法)。其他语言
github.com/fsnotify/fsnotify
库(跨平台,封装inotify)。org.apache.commons.io.monitor
或第三方库。递归监控限制
opendir
/readdir
)。inotifywait -r
实现递归(非API方式)。性能优化
权限问题
EACCES
错误。man inotify
(需安装manpages-dev
包)。/usr/include/linux/inotify.h
(包含事件类型和函数原型)。通过以上步骤,可在Ubuntu系统中高效使用inotify API实现文件系统监控。