在 Debian(以及所有 Linux 系统)里,readdir 并不是系统调用(system call),而是一个 C 库函数(glibc 函数)。
下面分层说明,避免混淆:
readdir 是什么readdir 是 POSIX 标准定义的 目录读取函数,声明在:
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
作用:
从已打开的目录流(DIR *)中读取下一个目录项。
readdir 在底层依赖什么系统调用readdir 在 glibc 中通常是这样实现的:
getdents / getdents64 系统调用struct dirent对应系统调用:
getdents(unsigned int fd, struct linux_dirent *dirp, unsigned int count);
getdents64(...)
可以用 strace 看到:
strace ls /tmp
通常会看到:
openat(AT_FDCWD, "/tmp", O_RDONLY|O_NONBLOCK|O_DIRECTORY) = 3
getdents64(3, /* entries */, 32768) = ...
| 层次 | 名称 | 类型 |
|---|---|---|
| 用户接口 | opendir |
glibc |
| 用户接口 | readdir |
glibc |
| 用户接口 | closedir |
glibc |
| 系统调用 | open / openat |
syscall |
| 系统调用 | getdents64 |
syscall |
| 系统调用 | close |
syscall |
man 2 readdir 在某些系统上能看到旧文档(历史原因)man 3 readdir # 库函数
man 2 getdents # 系统调用
Debian 中的
readdir是 glibc 提供的库函数,底层通过getdents64系统调用读取目录内容,本身不是系统调用。
如果你愿意,我也可以给你写一个 直接调用 getdents64 的最小示例,或者解释 readdir vs readdir_r 的区别。