安全地读取目录内容

发布于 2024-08-26 09:57:25 字数 146 浏览 5 评论 0原文

在该目录中创建或删除文件时,通过 readdir() 或 scandir() 读取目录条目是否安全?我应该选择其中之一而不是另一种吗?

编辑:当我说“安全”时,我的意思是这些函数返回的条目是有效的,并且可以在不使程序崩溃的情况下进行操作。

谢谢。

Is it safe to read directory entries via readdir() or scandir() while files are being created or deleted in this directory? Should I prefer one over the other?

EDIT: When I say "safe" I mean entries returned by these functions are valid and can be operated without crashing the program.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁许谁一生繁华 2024-09-02 09:57:25

这取决于您所说的“安全”。它们是安全的,因为它们不应该使您的程序崩溃。但是,如果您在读取/扫描该目录时创建/删除文件,则您返回的文件集可能不是最新的。

当读取/扫描目录中的目录条目时,文件指针(目录只是一种特殊类型的文件)向前移动。但是,根据文件系统的不同,可能没有什么可以阻止在文件指针后面的空目录项槽中创建新文件。因此,新添加的目录条目可能无法立即被 readdir()/scandir() 检测到。类似的推理适用于文件删除/目录条目删除。

希望这有帮助。

It depends by what you mean as "safe". They are safe in the sense that they should not crash your program. However, if you are creating/deleting files as you are reading/scanning that directory, the set of files you get back might not be up-to-date.

When reading/scanning a directory for directory entries, the file pointer (a directory is just a special type of file), moves forward. However, depending upon the file system, there may be nothing to prevent new files from being created in an empty directory entry slot behind your file pointer. Consequently, newly added directory entries may not be immediately detected by readdir()/scandir(). Similar reasoning applies for file deletion / directory entry removal.

Hope this helps.

装迷糊 2024-09-02 09:57:25

你对安全的定义是什么?您不会使系统崩溃,并且 readdir/scandir 不会使您的程序崩溃。尽管他们可能会为您提供立即过时的数据。

读取目录的通常语义是,如果您从头到尾读取目录,您将看到在该时间段内所有未更改的文件一次,并且您将看到在该时间段内创建或删除的文件最多一次。

在类 UNIX 系统上,readdir() 和 scandir() 是在同一底层系统调用(Linux 中的 getdents(),BSD 中的 getdirentries())之上实现的库函数。所以他们在这方面的行为应该不会有太大差异。我认为 readdir() 更标准一些,因此更便携。

What's your definition of safety? You won't crash the system, and readdir/scandir won't crash your program. Although they might give you data that is immediately out of date.

The usual semantics for reading a directory are that if you read the directory from beginning to end, you will see all of the files that didn't change during that time exactly once, and you will see files that were created or deleted during that time at most once.

On UNIX-like systems readdir() and scandir() are library functions implemented on top of the same underlying system call (getdents() in Linux, getdirentries() in BSD). So there shouldn't be much difference in their behavior in this regard. I think readdir() is a bit more standard, and therefore will be more portable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文