溫馨提示×

inotify如何檢測目錄變化

小樊
50
2025-09-02 16:59:05
欄目: 編程語言

inotify 是 Linux 系統中用于監控文件系統事件的一種機制。它能夠實時地檢測到文件或目錄的變化,如創建、刪除、修改等。要使用 inotify 檢測目錄變化,你需要使用 Linux 提供的 inotify API。

以下是一個簡單的示例,展示了如何使用 inotify 監控一個目錄的變化:

  1. 首先,確保你的系統已經安裝了 libinotify-dev 庫。在基于 Debian 的系統上,可以使用以下命令安裝:
sudo apt-get install libinotify-dev
  1. 創建一個名為 inotify_example.c 的 C 語言源文件,并添加以下代碼:
#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 <directory_to_monitor>\n", argv[0]);
        return 1;
    }

    // 初始化 inotify
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        return 1;
    }

    // 添加要監控的目錄
    wd = inotify_add_watch(fd, argv[1], IN_MODIFY | 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 created.\n", event->name);
                } else if (event->mask & IN_DELETE) {
                    printf("File %s deleted.\n", event->name);
                } else if (event->mask & IN_MODIFY) {
                    printf("File %s modified.\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

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

    return 0;
}
  1. 編譯源代碼:
gcc inotify_example.c -o inotify_example
  1. 運行程序,監控指定目錄:
./inotify_example /path/to/directory

這個示例程序會監控指定的目錄,并在文件發生變化時輸出相應的信息。你可以根據需要修改代碼以處理其他類型的事件或執行其他操作。

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