在Ubuntu系統中,inotify
是一個用于監控文件系統事件的Linux內核子系統。要使用inotify
檢測文件修改,你可以使用多種編程語言實現,比如C、Python等。以下是使用Python的inotify
庫來檢測文件修改的方法:
inotify
庫。如果沒有安裝,可以使用pip進行安裝:pip install inotify
import os
from inotify_simple import INotify, flags
# 初始化inotify實例
inotify = INotify()
# 監控的文件或目錄路徑
file_path = '/path/to/your/file'
# 添加監控事件
watch_flags = flags.MODIFY | flags.CLOSE_WRITE
wd = inotify.add_watch(file_path, watch_flags)
try:
while True:
# 讀取事件
for event in inotify.read():
if event.mask & flags.MODIFY:
print(f'File {event.name} was modified.')
elif event.mask & flags.CLOSE_WRITE:
print(f'File {event.name} was closed after being written.')
except KeyboardInterrupt:
# 移除監控并退出
inotify.rm_watch(wd)
print('Monitoring stopped.')
python your_script.py
這個腳本會監控指定的文件,當文件被修改或關閉寫入時,它會打印出相應的消息。
請注意,inotify
有一定的限制,比如監控的文件描述符數量和事件數量。如果你需要監控大量的文件或目錄,可能需要調整系統設置或者使用更高級的工具,如fswatch
或watchdog
。