在Debian系統中,使用inotify API可以監控文件系統事件,如文件的創建、刪除、修改等。以下是使用inotify API的基本步驟:
首先,確保你已經安裝了libinotify-dev庫,這是使用inotify API所需的開發庫。
sudo apt-get update
sudo apt-get install libinotify-dev
下面是一個簡單的C語言示例,演示如何使用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];
// 檢查命令行參數
if (argc != 2) {
printf("Usage: %s <directory_to_watch>\n", argv[0]);
exit(EXIT_FAILURE);
}
// 創建inotify實例
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
// 添加監控目錄
wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
printf("Monitoring directory: %s\n", argv[1]);
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
exit(EXIT_FAILURE);
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s created.\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("File %s deleted.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("File %s modified.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除監控并關閉inotify實例
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
使用gcc編譯上述代碼:
gcc -o inotify_example inotify_example.c -linotify
運行編譯后的程序,并指定要監控的目錄:
./inotify_example /path/to/directory
inotify_init(): 初始化inotify實例并返回文件描述符。inotify_add_watch(fd, path, mask): 添加一個監控項,fd是inotify實例的文件描述符,path是要監控的目錄路徑,mask是事件掩碼,指定要監控的事件類型。read(fd, buffer, BUF_LEN): 讀取inotify事件到緩沖區。struct inotify_event: 表示一個inotify事件,包含事件類型和文件名等信息。inotify_rm_watch(fd, wd): 移除監控項。close(fd): 關閉inotify實例。通過這些步驟,你可以在Debian系統中使用inotify API來監控文件系統的變化。