溫馨提示×

inotify如何檢測文件變化

小樊
50
2025-09-27 09:03:07
欄目: 編程語言

inotify 是 Linux 內核提供的一種文件系統事件監控機制,它可以實時監測文件或目錄的變化,如創建、刪除、修改等。以下是使用 inotify 檢測文件變化的步驟:

1. 安裝必要的庫

在大多數 Linux 發行版中,inotify 相關的功能已經包含在內核中,但你需要安裝一些庫來方便使用。例如,在 Debian/Ubuntu 系統上,你可以安裝 libinotify-dev

sudo apt-get update
sudo apt-get install libinotify-dev

2. 編寫代碼

以下是一個簡單的 C 語言示例,展示如何使用 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;
    }

    // 添加要監控的文件或目錄
    wd = inotify_add_watch(fd, "/path/to/your/file_or_directory", IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        close(fd);
        return 1;
    }

    printf("Monitoring file or directory for changes...\n");

    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
            break;
        }

        while (i < length) {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->len) {
                if (event->mask & IN_MODIFY) {
                    printf("File modified: %s\n", event->name);
                }
                if (event->mask & IN_CREATE) {
                    printf("File created: %s\n", event->name);
                }
                if (event->mask & IN_DELETE) {
                    printf("File deleted: %s\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除監控并關閉文件描述符
    inotify_rm_watch(fd, wd);
    close(fd);

    return 0;
}

3. 編譯和運行代碼

使用 gcc 編譯上述代碼:

gcc -o inotify_example inotify_example.c -linotify

然后運行生成的可執行文件:

./inotify_example

4. 解釋代碼

  • inotify_init(): 創建一個新的 inotify 實例并返回文件描述符。
  • inotify_add_watch(): 添加要監控的文件或目錄,并指定感興趣的事件(如 IN_MODIFY, IN_CREATE, IN_DELETE)。
  • read(): 從 inotify 文件描述符讀取事件。
  • struct inotify_event: 包含事件信息的結構體,通過解析它可以獲取事件的類型和文件名。

注意事項

  • inotify 有監控數量的限制,可以通過調整內核參數來增加限制。
  • 監控大量文件或目錄時,可能需要優化代碼以提高性能。

通過以上步驟,你可以使用 inotify 實現對文件變化的實時監控。

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