在 CentOS 上遇到 readdir()(目录遍历)慢的问题,通常不是单一原因,而是文件系统、磁盘、参数配置或业务用法综合导致的。下面按「常见原因 → 排查方法 → 解决建议」给你一个系统思路。
readdir 在以下情况会明显变慢:
检查:
ls -1 | wc -l
建议:
readdir 需要读 inode + 目录项
查看磁盘负载:
iostat -x 1
如果:
%util 接近 100%await 很高说明是磁盘 IO 问题。
解决:
这是最常见坑之一
actimeo 设置不合理noac查看挂载:
mount | grep nfs
优化示例:
mount -o rw,noatime,nodiratime,actimeo=60 nfs:/data /data
dir_indextune2fs -l /dev/sdX | grep "Filesystem features"
如果没有 dir_index:
tune2fs -O dir_index /dev/sdX
e2fsck -f /dev/sdX
常见罪魁:
clamavauditdinotify 监听过多检查:
ps aux | grep -E "clam|audit"
ls /proc/*/fd | xargs readlink 2>/dev/null | grep inotify
解决:
❌ 错误用法:
while ((ent = readdir(dir))) {
stat(ent->d_name); // 每个文件都 stat
}
✅ 更好:
readdir()
// 只在必要时 stat
或:
getdents()(系统调用级)scandir() 缓存结果mount -o remount,noatime,nodiratime /
ulimit -n 100000
/etc/security/limits.conf:
* soft nofile 100000
* hard nofile 100000
sysctl vm.vfs_cache_pressure=50
# IO
iostat -x 1
# 目录大小
ls -1 | wc -l
# 挂载
mount
# 文件系统
df -T
# 系统调用级别
strace -e trace=file your_command
你可以补充:
我可以直接给你针对性优化方案。