为什么生产者需要锁定目录才能在Linux中创建新文件?

发布于 2025-01-19 15:46:41 字数 160 浏览 1 评论 0原文

有一个生产者将新文件下载到本地文件系统(它永远不会修改现有文件),还有一个消费者定期检查是否有新文件并读取新文件。

我有点困惑为什么生产者需要在创建新文件之前锁定目录,而消费者在读取新文件时需要锁定目录,因为现有文件不会被修改,所以不应该有问题当读者阅读时,作者编辑文件。

谢谢

There's a producer which will download new files to a local file system (it will never modify existing files), and a consumer which periodically checks if there are new files and reads the new files.

I'm a bit confused about why the producer needs to lock the directory before creating the new file, and the consumer lock the directory when it is reading the new file, since no existing files will ever be modified so there should be no issue of a writer editing a file while the reader is reading.

Thanks

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

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

发布评论

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

评论(1

木槿暧夏七纪年 2025-01-26 15:46:41

生成文件不是原子的。首先,创建一个空文件。然后它的内容被写入其中,可能通过多次写入。每次写入都会修改文件,因此您声称文件从未被修改的说法是错误的。

使用锁来确保使用者仅获取完整的文件。[1]

可以使用其他锁定方法。例如,生产者可以创建以 .tmp 为后缀的文件,然后在文件完成时将文件重命名(而不是复制)为正确的名称。如果消费者忽略以 .tmp 结尾的文件,那么它只会选取完整的文件。[2]


  1. 完整的意思是生产者永远不会添加到再来一次。但这并不意味着该文件包含应有的全部内容。如果生产者崩溃,并且自动释放锁,那么消费者可能只能收到一部分预期内容。

  2. 真正完整。生产者不仅不会再向其中添加内容,而且生产者打算写入文件的所有内容都已写入其中。 (除非在错误的时刻发生停电或发生类似的严重事件。)

Producing a file is not atomic. First, an empty file is created. Then its content is written to it, possibly over multiple writes. Each write modifies the file, so your claim the file is never modified is false.

A lock is being used to ensure that the consumer only picks up complete files.[1]

There are alternative approaches to locking that could be used. For example, the producer could create files suffixed with .tmp, then rename (not copy) the file to the correct name when the file is complete. If the consumer ignores files ending in .tmp, then it will only pick up complete files.[2]


  1. Complete in the sense that the producer will never add to it again. But that doesn't mean the file contains all that it should. If the producer crashes, and if that automatically releases the lock, the consumer may receive only a part of the intended contents.

  2. Truly complete. Not only will the producer never add to it again, but everything the producer intended to write to the file was written to it. (Short of a power failure at exactly the wrong moment or a similarly drastic event.)

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