在 CentOS(Linux 内核)里,readdir 本身是不能直接“监听”的,readdir 只是用户态读取目录内容的系统调用。如果你想“监听目录变化”,常见做法有下面几种:
CentOS 原生支持 inotify,可以监听目录的创建、删除、修改等事件。
#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);
}
}
yum install inotify-tools
inotifywait -m /path/to/dir
适合:
#include <sys/fanotify.h>
⚠️ 一般需要 root 权限。
LD_PRELOAD 劫持 readdir示例(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 |
如果你能说清楚:
我可以直接给你可运行代码。