inotify 是 Linux 内核提供的一种文件系统事件监控机制,它可以实时监控文件或目录的变化,如创建、删除、修改等。在 Ubuntu 上配置 inotify 通常涉及以下几个步骤:
安装 inotify-tools:
inotify-tools 是一个提供了 inotifywait 和 inotifywatch 命令行工具的软件包,可以用来监控文件系统事件。
打开终端,运行以下命令来安装 inotify-tools:
sudo apt-get update
sudo apt-get install inotify-tools
使用 inotifywait:
安装完成后,你可以使用 inotifywait 命令来监控文件或目录。例如,要监控当前目录下的所有文件变化,可以使用以下命令:
inotifywait -m -r .
参数说明:
-m 或 --monitor:持续监控而不是执行一次。-r 或 --recursive:递归监控目录及其子目录。.:指定要监控的目录,这里表示当前目录。你可以根据需要添加其他选项来定制监控行为,例如:
-e 或 --event:指定要监控的事件类型,如 create, delete, modify 等。-q 或 --quiet:减少输出信息,只显示事件发生时的简要信息。例如,要监控当前目录下所有 .txt 文件的创建和修改事件,可以使用:
inotifywait -m -r -e create,modify --format '%w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' -e modify,create .
编写脚本:
如果你需要更复杂的监控逻辑,可以编写自己的脚本来使用 inotifywait。例如,创建一个名为 monitor.sh 的脚本:
#!/bin/bash
inotifywait -m -r -e create,delete,modify --format '%w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' -e modify,create . |
while read path action; do
echo "The file '$path' appeared at $action"
# 在这里添加你的逻辑
done
赋予脚本执行权限并运行它:
chmod +x monitor.sh
./monitor.sh
系统服务:
如果你想让 inotify 监控作为系统服务运行,你可以创建一个 systemd 服务单元文件。例如,创建一个名为 inotify.service 的文件:
[Unit]
Description=Inotify File System Monitor
[Service]
ExecStart=/path/to/your/script/monitor.sh
Restart=always
User=yourusername
[Install]
WantedBy=multi-user.target
将 /path/to/your/script/monitor.sh 替换为你的脚本路径,yourusername 替换为你的用户名。然后启用并启动服务:
sudo systemctl enable inotify.service
sudo systemctl start inotify.service
请注意,inotify 有文件描述符数量的限制,如果监控的文件或目录非常多,可能会达到这个限制。可以通过调整内核参数来增加这个限制。编辑 /etc/sysctl.conf 文件,添加或修改以下行:
fs.inotify.max_user_watches=524288
然后运行 sudo sysctl -p 来应用更改。