Linux 上的原子文件创建?
如果文件不存在,我需要创建一个文件,这样尝试创建该文件的另一个进程就会失败。我需要在创建过程完成向其中写入实际数据之前将该文件视为“已创建”。
我读到了关于 O_EXCL
标志到 open()
的内容,所以似乎解决方案存在,但是我有几个问题:
- 您有这种技术的经验吗?有多好? (我想我不能拥有数据库级原子性,但是足够好......好吧,足够了)
- 我应该在
open()
之后立即关闭文件,以便将其视为已创建,然后重新打开它进行写入? - 有什么微妙之处需要注意吗?
I need to create a file if it does not exist, in a way that another process trying to create this file would fail. I need the file be considered "created" even before the creating process finished writing the actual data to it.
I read about O_EXCL
flag to open()
, so it seems that the solution exists, I have a few questions however:
- do you have experience with this technique? How good is it? (I guess I can't have a DB-level atomicity, but but good enough is... well, enough)
- should I immediately close the file after
open()
so that it is considered created, and then reopen it for writing? - are there any subtleties to be aware of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
open() 手册页 表示您的方法在 NFS 上可能会失败。
来自 O_EXCL 部分:
它提出了一个更通用的解决方案:
请参阅此网页的“使用文件作为锁”部分 了解有关各种问题和方法的更多详细信息。
The open() man page says your method may fail on NFS.
From the section on O_EXCL:
And it suggests a more general solution:
See the "Using Files as Locks" section of this Web page for more details on the various issues and approaches.
POSIX 说:
因此其他使用
O_EXCL
的进程会认为它一创建就打开了。POSIX says:
So other processes using
O_EXCL
will consider it opened as soon as it is created.