32

rename(tmppath, path)不先打电话就打电话安全fsync(tmppath_fd)吗?

我希望路径始终指向一个完整的文件。我主要关心Ext4。rename() 是否承诺在所有未来的 Linux 内核版本中都是安全的?

Python中的一个使用示例:

def store_atomically(path, data):
    tmppath = path + ".tmp"
    output = open(tmppath, "wb")
    output.write(data)

    output.flush()
    os.fsync(output.fileno())  # The needed fsync().
    output.close()
    os.rename(tmppath, path)
4

3 回答 3

33

不。

查看 libeatmydata 和此演示文稿:

吃掉我的数据:每个人如何获取文件 IO 错误

http://www.oscon.com/oscon2008/public/schedule/detail/3172

来自 MySql 的 Stewart Smith。

如果它离线/不再可用,我会保留一份副本:

于 2011-09-15T15:09:14.690 回答
3

来自ext4 文档

When mounting an ext4 filesystem, the following option are accepted:
(*) == default

auto_da_alloc(*)    Many broken applications don't use fsync() when 
noauto_da_alloc     replacing existing files via patterns such as
                    fd = open("foo.new")/write(fd,..)/close(fd)/
                    rename("foo.new", "foo"), or worse yet,
                    fd = open("foo", O_TRUNC)/write(fd,..)/close(fd).
                    If auto_da_alloc is enabled, ext4 will detect
                    the replace-via-rename and replace-via-truncate
                    patterns and force that any delayed allocation
                    blocks are allocated such that at the next
                    journal commit, in the default data=ordered
                    mode, the data blocks of the new file are forced
                    to disk before the rename() operation is
                    committed.  This provides roughly the same level
                    of guarantees as ext3, and avoids the
                    "zero-length" problem that can happen when a
                    system crashes before the delayed allocation
                    blocks are forced to disk.

从“损坏的应用程序”的措辞来看,ext4 开发人员肯定认为这是一种不好的做法,但实际上它是如此广泛使用的方法,以至于它在 ext4 本身中被修补了。

因此,如果您的使用符合模式,您应该是安全的。

如果没有,我建议您进一步调查,而不是fsync为了安全起见在这里和那里插入。这可能不是一个好主意,因为fsync可能会对 ext3 ( read ) 造成重大影响。

另一方面,在重命名之前刷新是在非日志文件系统上进行替换的正确方法。也许这就是为什么 ext4 最初期望程序会出现这种行为,auto_da_alloc后来添加了该选项作为修复。此外,这个用于写回(非日志)模式的 ext3 补丁试图通过在重命名时异步刷新来帮助粗心的程序,以降低数据丢失的机会。

您可以在此处阅读有关 ext4 问题的更多信息。

于 2016-12-28T13:06:46.173 回答
1

如果您只关心 ext4 而不是 ext3,那么我建议您在重命名之前对新文件使用 fsync。ext4 上的 fsync 性能似乎比 ext3 上的要好得多,而且没有很长的延迟。或者可能是写回是默认模式(至少在我的 Linux 系统上)。

如果您只关心文件是否完整而不关心目录中的哪个文件,那么您只需要 fsync 新文件。也不需要 fsync 目录,因为它会指向包含完整数据的新文件或旧文件。

于 2011-09-15T16:02:37.607 回答