inotify
是 Linux 內核提供的一種文件系統事件監控機制,它可以實時監測文件或目錄的變化,如創建、刪除、修改等。以下是使用 inotify
檢測文件變化的步驟:
在大多數 Linux 發行版中,inotify
相關的功能已經包含在內核中,但你需要安裝一些庫來方便使用。例如,在 Debian/Ubuntu 系統上,你可以安裝 libinotify-dev
:
sudo apt-get update
sudo apt-get install libinotify-dev
以下是一個簡單的 C 語言示例,展示如何使用 inotify
監控文件變化:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int main(int argc, char **argv) {
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
// 創建 inotify 實例
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return 1;
}
// 添加要監控的文件或目錄
wd = inotify_add_watch(fd, "/path/to/your/file_or_directory", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return 1;
}
printf("Monitoring file or directory for changes...\n");
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
break;
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_MODIFY) {
printf("File modified: %s\n", event->name);
}
if (event->mask & IN_CREATE) {
printf("File created: %s\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("File deleted: %s\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除監控并關閉文件描述符
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
使用 gcc
編譯上述代碼:
gcc -o inotify_example inotify_example.c -linotify
然后運行生成的可執行文件:
./inotify_example
inotify_init()
: 創建一個新的 inotify
實例并返回文件描述符。inotify_add_watch()
: 添加要監控的文件或目錄,并指定感興趣的事件(如 IN_MODIFY
, IN_CREATE
, IN_DELETE
)。read()
: 從 inotify
文件描述符讀取事件。struct inotify_event
: 包含事件信息的結構體,通過解析它可以獲取事件的類型和文件名。inotify
有監控數量的限制,可以通過調整內核參數來增加限制。通過以上步驟,你可以使用 inotify
實現對文件變化的實時監控。