温馨提示×

centos readdir怎么监听

小樊
45
2026-10-12 00:05:14
栏目: 智能运维

在 CentOS(Linux 内核)里,readdir 本身是不能直接“监听”的,readdir 只是用户态读取目录内容的系统调用。如果你想“监听目录变化”,常见做法有下面几种:


一、最常用:inotify(推荐)

CentOS 原生支持 inotify,可以监听目录的创建、删除、修改等事件。

1. 监听目录示例(C 语言)

#include <sys/inotify.h>
#include <stdio.h>
#include <unistd.h>

int main() {
    int fd = inotify_init();
    int wd = inotify_add_watch(fd, "/path/to/dir",
        IN_CREATE | IN_DELETE | IN_MODIFY);

    char buf[4096];
    while (1) {
        int len = read(fd, buf, sizeof(buf));
        struct inotify_event *event = (struct inotify_event *)buf;
        if (event->mask & IN_CREATE)
            printf("文件创建: %s\n", event->name);
        if (event->mask & IN_DELETE)
            printf("文件删除: %s\n", event->name);
    }
}

2. 命令行方式(最方便)

yum install inotify-tools
inotifywait -m /path/to/dir

二、fanotify(更高级,内核级)

适合:

  • 审计
  • 安全监控
  • 需要看到“谁访问了文件”
#include <sys/fanotify.h>

⚠️ 一般需要 root 权限。


三、如果你是想“拦截 readdir”

情况 1:用户态程序

  • 无法直接监听
  • 只能通过:
    • LD_PRELOAD 劫持 readdir
    • ptrace 注入

示例(LD_PRELOAD):

#define _GNU_SOURCE
#include <dlfcn.h>
#include <dirent.h>

struct dirent *readdir(DIR *dirp) {
    static struct dirent *(*real_readdir)(DIR*) = NULL;
    if (!real_readdir)
        real_readdir = dlsym(RTLD_NEXT, "readdir");

    struct dirent *d = real_readdir(dirp);
    if (d) printf("readdir: %s\n", d->d_name);
    return d;
}

四、如果你只是想知道“目录什么时候变了”

✅ 用 inotify ❌ 不要轮询 readdir


总结

需求 方法
监听目录变化 inotify ✅
内核级监控 fanotify
拦截 readdir LD_PRELOAD / ptrace
文件系统级 auditd / ebpf

如果你能说清楚:

  • 是 C / Python / Shell
  • 想监听 哪个目录
  • 是 创建/删除/访问

我可以直接给你可运行代码。

0 踩