问题描述
我需要创建一个文件(如果该文件不存在),从而导致尝试创建该文件的另一个进程失败.即使在创建过程完成将实际数据写入文件之前,我仍需要将文件视为已创建".
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.
我阅读了有关open()
的O_EXCL
标志的信息,因此看来该解决方案存在,但是我有几个问题:
I read about O_EXCL
flag to open()
, so it seems that the solution exists, I have a few questions however:
- 您对此技术有经验吗?有多好? (我想我不能拥有数据库级别的原子性,但是足够好了……很好,足够了)
- 我应该在
open()
之后立即关闭文件,以便将其视为已创建,然后重新打开该文件以进行写入吗? - 有什么需要注意的微妙之处吗?
- 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?
推荐答案
open()手册页说您的方法可能无法在NFS上使用.
The open() man page says your method may fail on NFS.
在O_EXCL的部分中:
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.
这篇关于在Linux上创建原子文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!