inotify是Linux内核提供的文件系统事件监控机制,支持实时监听文件/目录的创建、删除、修改等操作,适用于自动化脚本、文件同步等场景。
命令行工具(快速上手)
编程接口(libinotify)
sudo apt install libinotify-dev。inotify_init():初始化监控实例。inotify_add_watch():添加监控路径及事件类型(如IN_CREATE、IN_MODIFY)。read():读取事件数据,解析struct inotify_event结构体。监控当前目录的文件创建和修改:
inotifywait -m -e create,modify . (-m表示持续监控,-e指定事件类型,.为当前目录)
递归监控目录并格式化输出:
inotifywait -m -r --format "%w%f %e" /path/to/directory (-r递归监控,--format自定义输出格式)
#include <stdio.h> #include <sys/inotify.h> #define EVENT_SIZE sizeof(struct inotify_event) #define BUF_LEN (1024 * (EVENT_SIZE + 16)) int main() { int fd = inotify_init(); if (fd < 0) { perror("inotify_init"); return 1; } // 监控当前目录的创建、删除、修改事件 int wd = inotify_add_watch(fd, ".", IN_CREATE | IN_DELETE | IN_MODIFY); if (wd < 0) { perror("inotify_add_watch"); return 1; } char buffer[BUF_LEN]; while (1) { int length = read(fd, buffer, BUF_LEN); if (length < 0) { perror("read"); break; } // 解析事件 for (int i = 0; i < length; ) { struct inotify_event *event = (struct inotify_event *)&buffer[i]; if (event->len) { if (event->mask & IN_CREATE) printf("Created: %s\n", event->name); else if (event->mask & IN_DELETE) printf("Deleted: %s\n", event->name); else if (event->mask & IN_MODIFY) printf("Modified: %s\n", event->name); } i += EVENT_SIZE + event->len; } } inotify_rm_watch(fd, wd); close(fd); return 0; } 编译运行:gcc -o inotify_example inotify_example.cpip install inotifyimport inotify.adapters i = inotify.adapters.Inotify() i.add_watch('/path/to/directory') for event in i.event_gen(): if event is not None: (header, type_names, watch_path, filename) = event print(f"Event: {type_names} | Path: {watch_path}/{filename}") (需安装inotify库,支持事件类型过滤)IN_CREATE(创建)、IN_DELETE(删除)、IN_MODIFY(修改)、IN_MOVED_FROM/TO(移动)。inotifywait -r或编程时对子目录逐个添加inotify_add_watch。/proc/sys/fs/inotify/max_user_watches增加监控上限。--exclude参数排除特定路径。inotifywait -m -e create /backup/dir | while read path file; do cp "$path/$file" "/backup/archive/$file" done systemd配置开机自启的监控任务。man inotifywait、man inotify_add_watch通过以上步骤,可在Debian上快速掌握inotify的事件驱动编程,满足文件监控需求。