溫馨提示×

inotify API如何使用

小樊
34
2025-08-21 16:02:12
欄目: 編程語言

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

  1. inotify_init(): 創建一個新的 inotify 實例并返回一個文件描述符。
  2. inotify_add_watch(): 添加一個監控項到 inotify 實例中,指定要監控的文件或目錄以及感興趣的事件。
  3. read(): 從 inotify 文件描述符中讀取事件。
  4. inotify_rm_watch(): 移除一個監控項。
  5. close(): 關閉 inotify 文件描述符。

下面是一個簡單的示例,展示如何使用 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, ".", IN_CREATE | IN_DELETE | IN_MODIFY);
    if (wd < 0) {
        perror("inotify_add_watch");
        return 1;
    }

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

編譯并運行這個程序,它將監控當前目錄下的文件變化,并在控制臺輸出相應的事件信息。

請注意,inotify API 的使用可能會受到一些限制,例如單個進程可以監控的文件描述符數量、監控的文件數量等。在實際應用中,可能需要根據具體需求進行調整和優化。

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