inotify是Linux內核提供的文件系統事件監控機制,能實時監測文件或目錄的創建、刪除、修改、移動等操作。在Ubuntu中,通常通過inotify-tools工具包(提供命令行工具)或編程接口(如C語言)使用inotify。
inotify-tools是Ubuntu下使用inotify的核心工具包,包含inotifywait(監控事件)和inotifywatch(統計事件)兩個命令。安裝步驟如下:
sudo apt update # 更新軟件包列表
sudo apt install inotify-tools # 安裝inotify-tools
安裝完成后,可通過inotifywait --help驗證是否成功。
inotifywait用于實時監控文件系統事件,以下是常見用法:
監控指定目錄的所有事件(默認監控第一層目錄):
inotifywait -m /path/to/directory
-m:持續監控(不退出),直到手動終止(Ctrl+C)。通過-e選項指定事件類型(可多選,用逗號分隔):
inotifywait -m -e create,delete,modify /path/to/directory
常用事件類型:
create:文件/目錄創建;delete:文件/目錄刪除;modify:文件內容修改;moved_to:文件/目錄移入;moved_from:文件/目錄移出。使用-r選項遞歸監控指定目錄及其所有子目錄:
inotifywait -m -r /path/to/directory
通過--exclude選項排除符合正則表達式的文件/目錄(如排除.log文件):
inotifywait -m -r --exclude '\.log$' /path/to/directory
使用--format選項定義輸出內容(如顯示文件路徑和事件類型):
inotifywait -m -e create,delete --format '%w%f %e' /path/to/directory
%w:監控路徑;%f:文件名;%e:事件類型。通過-t選項設置監控超時時間(秒),超時后自動退出:
inotifywait -m -t 60 /path/to/directory
inotifywatch用于統計指定時間內文件系統事件的發生次數,用法示例如下:
inotifywatch -m -r -t 60 /path/to/directory
-m:持續監控;-r:遞歸監控子目錄;-t 60:監控60秒后輸出統計結果(如各事件的發生次數)。若需要更靈活的監控邏輯(如集成到應用程序),可使用C語言調用inotify API。以下是簡單示例:
#include <sys/inotify.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init failed");
exit(EXIT_FAILURE);
}
inotify_init()創建inotify實例,返回文件描述符(fd)。
int wd = inotify_add_watch(fd, "/path/to/directory", IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch failed");
close(fd);
exit(EXIT_FAILURE);
}
inotify_add_watch()添加監控,參數說明:
fd:inotify實例文件描述符;"/path/to/directory":監控路徑;IN_CREATE | IN_DELETE | IN_MODIFY:監控事件類型(可組合)。char buffer[4096];
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
perror("read failed");
inotify_rm_watch(fd, wd);
close(fd);
exit(EXIT_FAILURE);
}
for (int i = 0; i < length; ) {
struct inotify_event *event = (struct inotify_event *)&buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("Created: %s\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("Deleted: %s\n", event->name);
}
if (event->mask & IN_MODIFY) {
printf("Modified: %s\n", event->name);
}
}
i += sizeof(struct inotify_event) + event->len;
}
read(fd, buffer, sizeof(buffer)):阻塞讀取事件(無事件時等待);struct inotify_event:內核返回的事件結構體,包含事件類型(mask)和文件名(name)。inotify_rm_watch(fd, wd); // 移除監控
close(fd); // 關閉inotify實例
/proc/sys/fs/inotify/max_user_watches調整(如echo 524288 | sudo tee /proc/sys/fs/inotify/max_user_watches);