在Ubuntu系统中配置和使用inotify的步骤如下:
首先,确保你已经安装了inotify-tools,这是一个常用的命令行工具集,用于与inotify交互。
sudo apt-get update
sudo apt-get install inotify-tools
inotifywait -m /path/to/your/file
inotifywait -m /path/to/your/directory
inotifywait -m /path/to/your/file /path/to/your/directory
inotifywait -m -e modify,closed_write /path/to/your/file
inotifywait -t 10 -m /path/to/your/file
inotifywait -m -v /path/to/your/file
你可以将inotifywait命令放入一个shell脚本中,以便自动化监控任务。例如,创建一个名为monitor.sh的脚本:
#!/bin/bash
inotifywait -m -e modify,closed_write /path/to/your/file |
while read path action file; do
echo "The file '$file' appeared in directory '$path' via event '$action'"
done
然后给脚本执行权限并运行它:
chmod +x monitor.sh
./monitor.sh
以下是一个使用Python和pyinotify库的示例:
pip install pyinotify
import pyinotify
class MyEventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
print(f"File {event.pathname} created")
def process_IN_DELETE(self, event):
print(f"File {event.pathname} deleted")
def process_IN_MODIFY(self, event):
print(f"File {event.pathname} modified")
watch_manager = pyinotify.WatchManager()
notifier = pyinotify.Notifier(watch_manager, MyEventHandler())
watch_manager.add_watch('/path/to/directory', pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY, rec=True)
notifier.loop()
通过以上步骤,你可以在Ubuntu系统中使用inotify实现实时文件系统监控。