CentOS 上用好 inotify 的关键技巧
一 安装与快速上手
sudo yum install -y epel-release && sudo yum install -y inotify-tools。ls /proc/sys/fs/inotify(应看到 max_user_watches、max_user_instances、max_queued_events)。inotifywait -m -r -e create,modify,delete,move /pathinotifywatch -r -e create,modify,delete /path二 高效监控与脚本编写
--format 定制字段,配合 --timefmt 统一时间格式,便于落库或对接告警。示例:inotifywait -m -r -q --timefmt '%F %T' --format '%T %w%f %e' -e create,modify,delete /data三 常见场景与命令示例
#!/usr/bin/env bash
SRC=/data/src
DST=/data/dst
inotifywait -m -r -e create,modify,delete,move "$SRC" --format '%w%f %e' | \
while IFS= read -r file event; do
rsync -a --update "$file" "$DST${file#$SRC}"
done
四 调优与排错要点
sudo sysctl -w fs.inotify.max_user_watches=524288echo "fs.inotify.max_user_watches=524288" | sudo tee -a /etc/sysctl.conf && sudo sysctl -pmax_user_instances(实例上限)、max_queued_events(队列上限,过小会出现 IN_Q_OVERFLOW)。find /path -type d | wc -l 预估,确保 max_user_watches 大于该值并留有余量。cat /proc/sys/fs/inotify/max_user_watches;若频繁出现队列溢出,适当增大 max_queued_events 并优化事件处理逻辑。