inotify 是 Linux 系統提供的一種文件系統事件監控機制,可以用來實時監控文件或目錄的變化。以下是使用 inotify 實現實時監控的基本步驟:
在大多數 Linux 發行版中,inotify 工具和庫已經預裝。如果沒有,可以使用包管理器進行安裝。
sudo apt-get install inotify-tools # Debian/Ubuntu
sudo yum install inotify-tools # CentOS/RHEL
inotifywait 命令inotifywait 是一個命令行工具,可以用來監控文件或目錄的變化。
inotifywait -m /path/to/file -e modify,attrib,close_write,move,create,delete
inotifywait -m /path/to/directory -e modify,attrib,close_write,move,create,delete
inotify API 編程如果你需要在自己的應用程序中實現實時監控,可以使用 inotify API。
#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");
}
// 添加監控目錄
wd = inotify_add_watch(fd, "/path/to/directory", IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_MOVE | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
}
// 監控事件
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s was created.\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("File %s was modified.\n", event->name);
} else if (event->mask & IN_ATTRIB) {
printf("File %s attributes were changed.\n", event->name);
} else if (event->mask & IN_CLOSE_WRITE) {
printf("File %s was closed after being written to.\n", event->name);
} else if (event->mask & IN_MOVE) {
printf("File %s was moved.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除監控并關閉 inotify 實例
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
在監控過程中,你可以根據不同的事件類型執行相應的操作。例如,當檢測到文件創建時,可以自動備份文件;當檢測到文件刪除時,可以記錄日志等。
inotify 有監控數量的限制,可以通過調整內核參數來增加監控數量。通過以上步驟,你可以使用 inotify 實現對文件或目錄的實時監控。