inotify 是 Linux 内核提供的文件系统事件监控机制,Ubuntu 下通常配合 inotify-tools 或 编程接口(C / Python) 使用。下面从命令行和编程两个层面讲清楚。
sudo apt update
sudo apt install inotify-tools
主要用两个:
inotifywait:等待事件发生inotifywatch:统计事件inotifywait -m -r -e create,delete,modify /path/to/dir
参数说明:
-m:持续监控(monitor)-r:递归子目录-e:指定事件/path/to/dir:监控路径示例输出:
/path/to/dir/ CREATE file.txt
/path/to/dir/ MODIFY file.txt
inotifywait -m -r -e close_write /data |
while read path action file
do
echo "文件变动: $path$file ($action)"
done
常见事件类型:
createdeletemodifymoveattribclose_writeinotifywatch -v -t 60 -r /path/to/dir
统计 60 秒内事件次数。
cat /proc/sys/fs/inotify/max_user_watches
echo 524288 | sudo tee /proc/sys/fs/inotify/max_user_watches
永久生效:
echo "fs.inotify.max_user_watches=524288" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
import inotify.adapters
notifier = inotify.adapters.Inotify()
notifier.add_watch('/path/to/dir')
for event in notifier.event_gen(yield_nones=False):
(_, type_names, path, filename) = event
print(f"{path}/{filename}: {type_names}")
安装:
pip install inotify
主要函数:
inotify_init()inotify_add_watch()read()inotify_rm_watch()适合写系统级工具。
如果你愿意,可以告诉我:
我可以直接给你可用脚本。