在Linux中,inotify(即Linux的文件系統事件監控機制)提供了幾個關鍵的API接口,用于監控文件或目錄的變化。以下是一些主要的inotify API接口:
int inotify_init(void);
int inotify_add_watch(int fd, const char *path, uint32_t mask);
fd
是由 inotify_init()
返回的文件描述符。path
是要監控的路徑。mask
是事件掩碼,定義了要監控的事件類型,例如 IN_MODIFY
, IN_CREATE
, IN_DELETE
等。ssize_t read(int fd, void *buf, size_t count);
fd
是inotify實例的文件描述符。buf
是用于存儲事件的緩沖區。count
是緩沖區的大小。int inotify_rm_watch(int fd, int wd);
fd
是inotify實例的文件描述符。wd
是由 inotify_add_watch()
返回的監視描述符(watch descriptor)。int close(int fd);
struct inotify_event
int wd;
:監視描述符。uint32_t mask;
:事件掩碼。uint32_t cookie;
:用于關聯事件的唯一標識符。uint32_t len;
:事件名稱的長度。char name[];
:事件名稱(可變長度數組)。IN_ACCESS
:文件被訪問。IN_MODIFY
:文件被修改。IN_ATTRIB
:文件屬性被修改。IN_CLOSE_WRITE
:文件在寫入后被關閉。IN_CLOSE_NOWRITE
:文件在沒有寫入的情況下被關閉。IN_OPEN
:文件被打開。IN_MOVED_FROM
:文件從一個目錄移動到另一個目錄。IN_MOVED_TO
:文件被移動到一個目錄。IN_CREATE
:文件或目錄被創建。IN_DELETE
:文件或目錄被刪除。IN_DELETE_SELF
:監控的文件或目錄被刪除。IN_MOVE_SELF
:監控的文件或目錄被移動。以下是一個簡單的示例,展示如何使用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");
return 1;
}
// 添加監控
wd = inotify_add_watch(fd, "/path/to/directory", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return 1;
}
// 讀取事件
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_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);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除監控并關閉inotify實例
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
這個示例程序會監控指定目錄中的文件創建、刪除和修改事件,并在控制臺輸出相關信息。
通過這些API接口,開發者可以靈活地實現對文件系統事件的監控和處理。