inotify
是 Linux 系統中用于監控文件系統事件的機制。要設置 inotify
的事件掩碼,您需要使用 inotify_init
或 inotify_init1
函數創建一個 inotify
實例,然后使用 inotify_add_watch
函數為該實例添加監控目錄,并指定所需的事件掩碼。
以下是一個簡單的示例,演示如何使用 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;
}
// 添加監控目錄,設置事件掩碼為 IN_CREATE | IN_DELETE
wd = inotify_add_watch(fd, "/path/to/directory", IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
return 1;
}
// 讀取 inotify 事件
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
return 1;
}
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);
}
if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除監控并關閉 inotify 實例
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
在這個示例中,我們使用 inotify_add_watch
函數添加了一個監控目錄,并設置了事件掩碼為 IN_CREATE | IN_DELETE
,這意味著我們將監控目錄中的文件創建和刪除事件。事件掩碼可以包含多個事件,例如 IN_MODIFY
(文件修改)、IN_ATTRIB
(文件屬性更改)等。您可以參考 inotify
的手冊頁(man 7 inotify
)以獲取完整的事件列表。
請注意,這個示例僅用于演示目的,實際應用中可能需要處理更多的錯誤情況和邊界條件。