在 Debian 下使用 opendir()(通常是 C/C++ 的 opendir(3))报错时,排查思路一般如下:
opendir() 本身返回 NULL 并设置 errno,一定要看 errno:
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <dirent.h>
DIR *dir = opendir(path);
if (!dir) {
fprintf(stderr, "opendir failed: %s\n", strerror(errno));
}
常见 errno:
ENOENT:目录不存在EACCES:权限不足ENOTDIR:不是目录EMFILE / ENFILE:打开文件数过多ENOMEM:内存不足ls -ld /your/path
ls -ld /path/to/dir
id
aa-status
如果是容器或 systemd 服务,可能受限制。
opendir 报错mount | grep path
df -h path
ulimit -n
lsof -p <pid> | wc -l
代码中是否 忘记 closedir()。
ls -l /path
readlink -f /path
opendir 不会自动解析错误符号链接。
ProtectHome=, PrivateTmp= 影响#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(int argc, char **argv) {
if (argc < 2) return 1;
DIR *d = opendir(argv[1]);
if (!d) {
printf("errno=%d: %s\n", errno, strerror(errno));
return 1;
}
closedir(d);
return 0;
}
编译运行:
gcc test.c -o test
./test /some/path
strace:strace ./your_program /path
看 openat() / opendir() 系统调用
如果你能贴出:
strerror(errno))cat /etc/debian_version)我可以更精确地帮你定位。