溫馨提示×

如何利用Linux readdir進行文件監控

小樊
43
2025-10-06 19:54:55
欄目: 智能運維

在Linux系統中,readdir函數通常用于讀取目錄的內容。然而,如果你想要實現文件監控,即實時檢測目錄中文件的變化(如新增、刪除或修改),readdir本身并不直接提供這樣的功能。你需要結合其他機制來實現這一目標。

以下是一些常用的方法來監控Linux目錄中的文件變化:

1. 使用 inotify

inotify 是Linux內核提供的一種文件系統事件監控機制。你可以使用 inotify 來監控目錄中的文件變化。

示例代碼(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, "/path/to/directory", IN_MODIFY | IN_CREATE | IN_DELETE);
    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 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;
}

2. 使用 fswatch

fswatch 是一個第三方工具,可以監控文件系統事件并執行命令。

安裝 fswatch

sudo apt-get install fswatch  # Debian/Ubuntu
sudo yum install fswatch      # CentOS/RHEL

使用示例:

fswatch -o /path/to/directory | while read path; do
    echo "File $path changed"
done

3. 使用 inotifywait

inotifywaitinotify-tools 包中的一個工具,可以等待并打印文件系統事件。

安裝 inotify-tools

sudo apt-get install inotify-tools  # Debian/Ubuntu
sudo yum install inotify-tools      # CentOS/RHEL

使用示例:

inotifywait -m -r -e create,delete,modify /path/to/directory

4. 使用 lsdiff

你可以定期運行 ls 命令并比較結果來檢測文件變化。

示例腳本:

#!/bin/bash

DIR="/path/to/directory"
PREV_FILE_LIST=$(ls $DIR)

while true; do
    CURRENT_FILE_LIST=$(ls $DIR)
    DIFF=$(diff <(echo "$PREV_FILE_LIST") <(echo "$CURRENT_FILE_LIST"))
    if [ -n "$DIFF" ]; then
        echo "Files have changed:"
        echo "$DIFF"
        PREV_FILE_LIST=$CURRENT_FILE_LIST
    fi
    sleep 1
done

總結

  • inotify 是最直接和高效的方法,適用于需要實時監控的場景。
  • fswatchinotifywait 是第三方工具,使用簡單,適合快速實現監控功能。
  • 使用 lsdiff 的方法雖然簡單,但效率較低,適用于文件變化不頻繁的場景。

選擇哪種方法取決于你的具體需求和環境。

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