安裝工具包
inotify-tools
(命令行工具,非API,用于快速測試):sudo apt-get update && sudo apt-get install inotify-tools
inotify
內核模塊(現代Ubuntu默認支持):lsmod | grep inotify # 檢查模塊是否加載
關鍵系統參數
cat /proc/sys/fs/inotify/max_user_watches # 單用戶最大監控項數
cat /proc/sys/fs/inotify/max_user_instances # 單用戶最大實例數
sudo sysctl -w fs.inotify.max_user_watches=524288
永久生效需修改 /etc/sysctl.conf
并執行 sysctl -p
。創建inotify實例
#include <sys/inotify.h>
int fd = inotify_init();
if (fd < 0) { perror("inotify_init failed"); exit(1); }
添加監控路徑
// 監控目錄(遞歸需手動處理子目錄)
int wd = inotify_add_watch(fd, "/path/to/directory",
IN_CREATE | IN_MODIFY | IN_DELETE);
if (wd < 0) { perror("inotify_add_watch failed"); exit(1); }
// 事件類型說明:
// IN_CREATE:文件/目錄創建
// IN_MODIFY:文件內容修改
// IN_DELETE:文件/目錄刪除
// 更多事件類型見
讀取事件
char buffer[1024];
ssize_t len = read(fd, buffer, sizeof(buffer));
if (len < 0) { perror("read failed"); exit(1); }
// 解析事件
struct inotify_event *event;
for (char *p = buffer; p < buffer + len; ) {
event = (struct inotify_event *)p;
if (event->len) {
printf("Event: %s, File: %s\n",
(event->mask & IN_CREATE) ? "CREATE" : "MODIFY/DELETE",
event->name);
}
p += sizeof(struct inotify_event) + event->len;
}
清理資源
inotify_rm_watch(fd, wd); // 移除監控
close(fd); // 關閉實例
Python(使用inotify
庫)
import inotify.adapters
notifier = inotify.adapters.Inotify()
notifier.add_watch('/path/to/directory',
mask=inotify.constants.IN_CREATE |
inotify.constants.IN_MODIFY |
inotify.constants.IN_DELETE)
for event in notifier.event_gen():
if event is not None:
print(f"Event: {event[1].maskname}, File: {event[2]}")
inotify-tools
的--recursive
選項或庫的特定方法)。其他語言
github.com/fsnotify/fsnotify
庫(跨平臺,封裝inotify)。org.apache.commons.io.monitor
或第三方庫。遞歸監控限制
opendir
/readdir
)。inotifywait -r
實現遞歸(非API方式)。性能優化
權限問題
EACCES
錯誤。man inotify
(需安裝manpages-dev
包)。/usr/include/linux/inotify.h
(包含事件類型和函數原型)。通過以上步驟,可在Ubuntu系統中高效使用inotify API實現文件系統監控。