algorithm - 遍历包含链接循环的目录树的有效方法

标签 algorithm filesystems symlink directory-walk symlink-traversal

是否有比跟踪哪些文件已被访问过更有效的方式来遍历包含链接循环的目录树?

例如,考虑遍历包含这些文件的目录:

symlink "parent" -> ".."
symlink "uh_oh" -> "/"
regular file "reg"
symlink "reg2" -> "reg"

最佳答案

根据您的第一个示例,您还应该跟踪访问了哪些目录,但除此之外,没有比为每个文件维护已访问标志更好的解决方案了。

如果有一种可移植的方法可以为已安装的文件系统获取一个简短的唯一标识符,那么维护这些标志会更容易。即使那样,您也需要考虑扫描期间发生的挂载和卸载操作的后果,特别是因为如果文件系统树包含远程文件系统,则此类扫描可能需要相当长的时间。

理论上,您可以从 stafvfs 中获取“文件系统 ID”接口(interface),但实际上并不完全可移植。从 Linux 发行版中引用 man statfs:

Nobody knows what f_fsid is supposed to contain…

…The general idea is that f_fsid contains some random stuff such that the pair (f_fsid,ino) uniquely determines a file. Some operating systems use (a variation on) the device number, or the device number combined with the filesystem type. Several OSes restrict giving out the f_fsid field to the superuser only (and zero it for unprivileged users), because this field is used in the filehandle of the filesystem when NFS-exported, and giving it out is a security concern.

后一种限制——f_fsid 对非特权用户显示为 0——并不违反上面引用的 Posix 标准,因为该标准包含一个非常通用的 disclaimer。 : "未指定 statvfs 结构的所有成员是否在所有文件系统上都具有有意义的值。"

关于algorithm - 遍历包含链接循环的目录树的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451089/

相关文章:

algorithm - 2-SAT变量值

在 O(log n) 中计算 x ^ y

node.js - nodejs - 如何读取和输出 jpg 图像?

java - 从 Linux 文件系统读取文件的时间复杂度是多少?

java - Ant 目标符号链接(symbolic link)在 Windows 上不起作用

Git将目录符号链接(symbolic link)创建为文件

algorithm - 大 N 值的矩阵求幂算法

algorithm - 使用 Map/Reduce 计算自举算法

ruby - 如何使用 Ruby listen gem 监控单个文件?

python - 尝试在 Windows 10 上使用 python 创建符号链接(symbolic link)时出现权限错误