温馨提示×

ubuntu readdir如何监听变化

小樊
40
2026-10-21 04:05:22
栏目: 智能运维

在 Ubuntu(Linux)下,readdir 本身不能监听目录变化。readdir 只是“读目录”,是一次性或迭代式的读取,没有事件通知能力。

如果你想“监听目录变化”,正确做法是用 inotify(或更高层封装)。下面按使用场景给你几种方案。


一、最推荐:inotify(Linux 原生)

1. C 语言示例(inotify + readdir 配合)

#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

二、Shell 方式(简单但不实时)

1. inotifywait(推荐)

sudo apt install inotify-tools

inotifywait -m -e create -e delete /path/to/dir

2. 轮询(不推荐)

while true; do
    ls /path/to/dir
    sleep 1
done

三、高级方案

1. fanotify(更底层,适合安全软件)

  • 可监听整个文件系统
  • 比 inotify 更强大,但更复杂

2. systemd path 单元

# /etc/systemd/system/watch.path
[Path]
PathModified=/path/to/dir

[Install]
WantedBy=multi-user.target
systemctl enable --now watch.path

四、常见误解澄清

❌ readdir 能监听变化
✅ readdir 只能读取当前目录内容

❌ 轮询目录 = 实时监听
✅ 实时监听必须用 inotify / fanotify


五、如果你愿意,我可以:

  • 给你 Python / Go / Rust 示例
  • 教你 递归监听子目录
  • 帮你解决 Docker / NFS 下 inotify 不生效
  • 帮你把 readdir 改成“首次扫描 + inotify 增量更新”

你用的是 C / Python / Shell / 其他语言?

0 踩