在Linux上创建原子文件? [英] atomic file creation on Linux?

查看:114
本文介绍了在Linux上创建原子文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个文件(如果该文件不存在),从而导致尝试创建该文件的另一个进程失败.即使在创建过程完成将实际数据写入文件之前,我仍需要将文件视为已创建".

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:

  1. 您对此技术有经验吗?有多好? (我想我不能拥有数据库级别的原子性,但是足够好了……很好,足够了)
  2. 我应该在open()之后立即关闭文件,以便将其视为已创建,然后重新打开该文件以进行写入吗?
  3. 有什么需要注意的微妙之处吗?
  1. 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)
  2. should I immediately close the file after open() so that it is considered created, and then reopen it for writing?
  3. 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:

与O_CREAT一起使用时,如果文件 已经存在,这是一个错误,并且 open()将失败.在这种情况下, 符号链接存在,无论 它指向的位置. O_EXCL损坏 在NFS文件系统上;哪些程序 依靠它来执行锁定 任务将包含竞赛条件.

When used with O_CREAT, if the file already exists it is an error and the open() will fail. In this context, a symbolic link exists, regardless of where it points to. O_EXCL is broken on NFS file systems; programs which rely on it for performing locking tasks will contain a race condition.

它提出了一个更通用的解决方案:

And it suggests a more general solution:

执行原子的解决方案 使用锁定文件锁定文件是为了 在同一文件上创建一个唯一文件 系统(例如,包含主机名 和pid),使用link(2)建立链接 到锁定文件.如果link()返回0, 锁定成功.否则,使用 stat(2)在唯一文件上检查 它的链接数已增加到2, 在这种情况下,锁也是 成功.

The solution for performing atomic file locking using a lockfile is to create a unique file on the same file system (e.g., incorporating hostname and pid), use link(2) to make a link to the lockfile. If link() returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful.

请参见该网页以获取有关各种问题和方法的更多详细信息.

See the "Using Files as Locks" section of this Web page for more details on the various issues and approaches.

这篇关于在Linux上创建原子文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆