溫馨提示×

Linux下如何用copendir實現目錄監控

小樊
51
2025-09-26 00:18:23
欄目: 智能運維

在 Linux 下,opendir 函數用于打開一個目錄流,以便你可以使用 readdir 函數讀取目錄中的條目。然而,opendir 本身并不提供直接的目錄監控功能。要實現目錄監控,你可以結合使用 inotify API 或輪詢目錄變化的方法。

下面是一個簡單的示例,展示如何使用 opendirreaddir 來遍歷目錄,并結合 inotify 來監控目錄變化:

使用 opendirreaddir 遍歷目錄

#include <stdio.h>
#include <stdlib.h>
#include <dirent.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 ) )

void list_directory(const char *path) {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(path);
    if (!dir) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
}

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return EXIT_FAILURE;
    }

    list_directory(argv[1]);

    // Initialize inotify
    int fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        return EXIT_FAILURE;
    }

    // Add watch for the directory
    int wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        close(fd);
        return EXIT_FAILURE;
    }

    // Read events from inotify
    char buffer[BUF_LEN];
    while (1) {
        ssize_t length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
            break;
        }

        int i = 0;
        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;
        }
    }

    // Remove watch and close inotify
    inotify_rm_watch(fd, wd);
    close(fd);

    return EXIT_SUCCESS;
}

解釋

  1. 遍歷目錄

    • 使用 opendir 打開目錄。
    • 使用 readdir 讀取目錄中的條目并打印。
  2. 監控目錄變化

    • 使用 inotify_init 初始化 inotify。
    • 使用 inotify_add_watch 添加對指定目錄的監控,監控事件包括文件修改、創建和刪除。
    • 使用 read 讀取 inotify 事件,并根據事件類型打印相應的消息。
    • 最后,使用 inotify_rm_watch 移除監控并關閉 inotify。

編譯和運行

gcc -o monitor_directory monitor_directory.c
./monitor_directory /path/to/directory

這個示例程序會遍歷指定目錄中的所有文件,并持續監控該目錄的變化,當有文件被修改、創建或刪除時,會打印相應的消息。

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