在Debian系統中,inotify是一個用于監控文件系統事件的Linux內核子系統。要在Debian中使用inotify API,你需要使用libinotify庫。以下是一些基本的inotify API調用方法:
sudo apt-get update
sudo apt-get install libinotify-dev
#include <sys/inotify.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
inotify_init()
函數創建一個新的inotify實例:int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
exit(EXIT_FAILURE);
}
inotify_add_watch()
函數為一個文件或目錄添加監控。例如,監控當前目錄下的所有文件:int wd = inotify_add_watch(fd, ".", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
exit(EXIT_FAILURE);
}
這里,我們監控了當前目錄(.
),并設置了三個事件:文件修改(IN_MODIFY)、文件創建(IN_CREATE)和文件刪除(IN_DELETE)。
read()
函數從inotify實例中讀取事件:char buffer[4096];
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
perror("read");
exit(EXIT_FAILURE);
}
inotify_event
,其中包含有關事件的詳細信息。int i = 0;
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_MODIFY) {
printf("File %s was modified\n", event->name);
}
if (event->mask & IN_CREATE) {
printf("File %s was created\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("File %s was deleted\n", event->name);
}
}
i += sizeof(struct inotify_event) + event->len;
}
inotify_rm_watch()
函數移除監控,并使用close()
函數關閉inotify實例:inotify_rm_watch(fd, wd);
close(fd);
這就是在Debian中使用inotify API的基本方法。你可以根據自己的需求調整這些示例代碼。