linux

如何利用Linux readdir进行文件监控

小樊
50
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

总结

选择哪种方法取决于你的具体需求和环境。

0
看了该问题的人还看了