Linux监控文件变化最主流、轻量又可靠的方式是inotify,基于内核事件驱动,需先安装inotify-tools,再用inotifywait命令或pyinotify库实现监听与响应。

Linux 监控文件变化最主流、轻量又可靠的方式就是 inotify,它基于内核事件驱动,不轮询、低开销、响应快。核心是 inotify-tools 工具集(尤其是 inotifywait),配合 shell 脚本或 Python 就能快速落地。
没安装就无法使用:
sudo apt update && sudo apt install inotify-tools
sudo dnf install inotify-tools
sudo yum install inotify-tools
装完运行 inotifywait --version 确认可用。
它适合命令行调试和简单自动化,常用组合示例:
inotifywait -m -r -e modify,create,delete,attrib /path/to/dir
inotifywait -m -e create --format '%w%f' /path/to/dir
inotifywait -m --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %w%f %e' -e modify /tmp/test.conf
注意:-m 表示持续监听;-r 启用递归;-e 可指定多个事件,避免无意义的 access 或 open 干扰。
把监控和动作串起来,比如配置更新后自动 reload 服务:
#!/bin/bash CONFIG="/etc/nginx/nginx.conf" while inotifywait -e modify "$CONFIG" >/dev/null; do nginx -t && systemctl reload nginx done
更健壮的做法是用管道捕获事件流:
inotifywait -m -e create --format '%w%f' /var/log/myapp | while read file; do curl -X POST --data-binary "@$file" http://api.example.com/upload; done
chmod +x,后台运行可用 nohup ./watch.sh & 或 systemd 管理。适合要过滤路径、多级判断、并发处理或集成进已有项目的情况:
pip install pyinotify
import pyinotify
class MyHandler(pyinotify.ProcessEvent):
def process_IN_MODIFY(self, event):
if event.pathname.endswith('.log'):
print(f"[LOG MODIFIED] {event.pathname}")
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, MyHandler())
wm.add_watch('/var/log', pyinotify.IN_MODIFY, rec=True)
notifier.loop()
支持递归、通配符匹配、事件去重、异步回调等,比纯 shell 更可控。
基本上就这些。inotify 不复杂但容易忽略细节——比如默认单用户最多监控 8192 个文件(/proc/sys/fs/inotify/max_user_watches),大目录要提前调高;再比如监控符号链接需确保目标有读权限。用对了,它就是 Linux 文件监控的“隐形守门员”。
以上就是Linux 怎么监控文件变化?inotify 实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号