在 Ubuntu(Linux)下,readdir 本身不能监听目录变化。readdir 只是“读目录”,是一次性或迭代式的读取,没有事件通知能力。
如果你想“监听目录变化”,正确做法是用 inotify(或更高层封装)。下面按使用场景给你几种方案。
#include <sys/inotify.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.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 *ev = (struct inotify_event *)buf;
if (ev->mask & IN_CREATE)
printf("文件创建: %s\n", ev->name);
if (ev->mask & IN_DELETE)
printf("文件删除: %s\n", ev->name);
}
}
编译:
gcc watch.c -o watch
inotifywait(推荐)sudo apt install inotify-tools
inotifywait -m -e create -e delete /path/to/dir
while true; do
ls /path/to/dir
sleep 1
done
# /etc/systemd/system/watch.path
[Path]
PathModified=/path/to/dir
[Install]
WantedBy=multi-user.target
systemctl enable --now watch.path
❌ readdir 能监听变化
✅ readdir 只能读取当前目录内容
❌ 轮询目录 = 实时监听
✅ 实时监听必须用 inotify / fanotify
readdir 改成“首次扫描 + inotify 增量更新”你用的是 C / Python / Shell / 其他语言?