溫馨提示×

inotify的API如何調用

小樊
49
2025-09-12 17:18:12
欄目: 編程語言

inotify 是 Linux 內核提供的一種文件系統事件監控機制,允許應用程序實時監控文件系統中的變化,如文件的創建、刪除、修改和移動等。inotify 的 API 主要包括以下幾個部分:

  1. 初始化 inotify 實例: 使用 inotify_init()inotify_init1() 函數來創建一個新的 inotify 實例。

    #include <sys/inotify.h>
    
    int inotify_init(void);
    int inotify_init1(int flags);
    

    inotify_init1() 允許你通過 flags 參數指定一些選項,例如 IN_NONBLOCK。

  2. 添加監控: 使用 inotify_add_watch() 函數來添加對特定文件或目錄的監控。

    int inotify_add_watch(int fd, const char *path, uint32_t mask);
    
    • fdinotify_init() 返回的文件描述符。
    • path 是你想要監控的文件或目錄的路徑。
    • mask 是一個位掩碼,指定了你想要監控的事件類型,例如 IN_MODIFY, IN_CREATE, IN_DELETE 等。
  3. 讀取事件: 使用 read() 系統調用從 inotify 文件描述符中讀取事件。

    ssize_t read(int fd, void *buf, size_t count);
    
    • fd 是 inotify 文件描述符。
    • buf 是一個緩沖區,用于存儲讀取的事件。
    • count 是緩沖區的大小。

    讀取到的事件結構體是 struct inotify_event,它包含了事件的相關信息,如事件類型、文件名等。

  4. 移除監控: 使用 inotify_rm_watch() 函數來移除之前添加的監控。

    int inotify_rm_watch(int fd, int watch_descriptor);
    
    • fd 是 inotify 文件描述符。
    • watch_descriptor 是由 inotify_add_watch() 返回的監控描述符。
  5. 關閉 inotify 實例: 當不再需要監控時,使用 close() 系統調用關閉 inotify 文件描述符。

    int close(int fd);
    

下面是一個簡單的示例,演示了如何使用 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 <file or directory to monitor>\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);
    }

    // 讀取事件
    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 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;
}

這個示例程序會監控命令行參數指定的文件或目錄,并在檢測到文件創建、刪除或修改事件時打印相應的消息。請注意,這個程序是一個無限循環,它會一直運行直到被外部信號終止。在實際應用中,你可能需要添加適當的退出邏輯。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女