在 CentOS 上,“监听 readdir”通常有两种理解,下面分别说明:
inotify(最常用,但不能精确监听 readdir)inotify 不能直接监听 readdir,只能监听:
yum install inotify-tools
inotifywait -m /path/to/dir
⚠️ 注意:
ls、readdir 不会触发 inotify 事件
auditd(推荐 ✅)auditd 可以监控 系统调用级别,包括 readdir
yum install audit
systemctl start auditd
systemctl enable auditd
auditctl -w /path/to/dir -p r -k dir_read
-w:监控路径-p r:读权限(包含 readdir)-k:自定义关键字ausearch -k dir_read
或实时看:
tail -f /var/log/audit/audit.log
示例日志:
type=SYSCALL msg=audit(...): arch=c000003e syscall=217 ...
(syscall=217 是 getdents / readdir)
bpftrace(高级 ✅)适合开发 / 内核级监控
bpftrace -e '
tracepoint:syscalls:sys_enter_getdents* {
printf("%s %s\n", comm, str(args->pathname));
}
'
如果你是 写程序,想拦截 readdir:
#define _GNU_SOURCE
#include <dirent.h>
#include <string.h>
struct dirent *readdir(DIR *dirp) {
static typeof(readdir) *real = NULL;
if (!real) real = dlsym(RTLD_NEXT, "readdir");
struct dirent *d = real(dirp);
if (d) printf("readdir: %s\n", d->d_name);
return d;
}
编译:
gcc -shared -fPIC hook.c -o hook.so -ldl
运行:
LD_PRELOAD=./hook.so ls
| 需求 | 推荐方案 |
|---|---|
| 监控谁读了目录 | auditd |
| 实时列目录变化 | inotify(非 readdir) |
| 开发/调试 | bpftrace |
| 程序级拦截 | LD_PRELOAD |
如果你能说清楚:
我可以给你更精确的方案。