溫馨提示×

inotify如何檢測文件創建

小樊
36
2025-09-02 16:58:05
欄目: 編程語言

inotify 是 Linux 內核提供的一種文件系統事件監控機制,可以用來檢測文件的創建、修改、刪除等事件。要使用 inotify 檢測文件創建,你可以使用 Linux 的 inotify-tools 工具集,或者直接使用 inotify API。

使用 inotify-tools

  1. 安裝 inotify-tools

    在大多數 Linux 發行版中,你可以使用包管理器來安裝 inotify-tools。例如,在基于 Debian 的系統上,可以使用以下命令:

    sudo apt-get install inotify-tools
    
  2. 使用 inotifywait 監控目錄

    inotifywaitinotify-tools 中的一個命令行工具,可以用來監控文件系統事件。以下是一個簡單的示例,用于監控當前目錄下的文件創建事件:

    inotifywait -m -e create --format '%w%f' .
    

    解釋:

    • -m:監控模式,持續監控而不是等待事件。
    • -e create:指定要監控的事件類型,這里是文件創建。
    • --format '%w%f':指定輸出格式,%w 表示文件所在的目錄,%f 表示文件名。
    • .:監控當前目錄。

使用 inotify API

如果你需要在自己的程序中使用 inotify,可以使用 Linux 提供的 inotify API。以下是一個簡單的 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];

    // 創建 inotify 實例
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        return 1;
    }

    // 添加監控目錄
    wd = inotify_add_watch(fd, ".", IN_CREATE);
    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);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除監控并關閉 inotify 實例
    inotify_rm_watch(fd, wd);
    close(fd);

    return 0;
}

編譯并運行這個程序:

gcc -o inotify_example inotify_example.c
./inotify_example

這個程序會持續監控當前目錄下的文件創建事件,并在檢測到文件創建時打印文件名。

通過這兩種方法,你可以使用 inotify 來檢測文件的創建事件。

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