inotify 是 Linux 内核提供的一种文件系统事件监控机制,全称是 inode notify。它可以让你实时监听文件或目录发生的变化,而不需要轮询(不断去查)。
可以监控的事件包括(常见):
典型应用:
rsync + inotify)核心系统调用:
inotify_init():创建 inotify 实例inotify_add_watch():添加监控read():读取事件inotify_rm_watch():移除监控Linux 提供了用户态工具:
inotifywait(来自 inotify-tools)inotifywait -m /tmp
示例:监听文件修改
inotifywait -m -e modify /var/log/app.log
安装:
# Debian / Ubuntu
apt install inotify-tools
# CentOS / Rocky
yum install inotify-tools
int fd = inotify_init();
int wd = inotify_add_watch(fd, "/tmp", IN_CREATE | IN_DELETE);
char buf[4096];
read(fd, buf, sizeof(buf));
max_user_watches 限制)查看限制:
cat /proc/sys/fs/inotify/max_user_watches
修改:
echo 524288 | tee /proc/sys/fs/inotify/max_user_watches
| 机制 | 特点 |
|---|---|
| inotify | Linux 原生,轻量 |
| fanotify | 更底层,可拦截 |
| polling | 简单但效率低 |
如果你愿意,我可以:
你想看哪一个?