在Linux上以原子方式交换两个文件的内容 [英] Atomically swap contents of two files on Linux

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

问题描述

我有两个文件AB,每个文件都有自己的内容.

I have two files, A and B, each with its own content.

我想交换这两个文件,所以A会变成B,而B会变成A.但是我想做一个保证,没有其他进程会发现这两个文件处于不一致状态,也没有任何进程会发现其中的任何文件丢失,即使是很短的时间.因此,作为附带的操作,我还要保证,如果在操作过程中发生任何错误,则什么都不会改变(我想这就像一笔交易).

I would like to swap these two files, so A would become B, and B would become A. But I would like to do with a guaranty that no other process will find these two files in an inconsistent state, nor any process will find any of those files missing, even for a short while. So, as a side operation, I would also like to have a guaranty that if anything would go wrong during the operation, nothing will be changed (kind of like a transaction I guess).

在OS X上有一个exchangedata()函数,所以我想我正在寻找与之等效的Linux,或者至少是进行原子文件交换的等效方法.

On OS X there is a exchangedata() function, so I guess I'm looking for a Linux equivalent of it, or at least an equivalent method for doing atomic file swap.

推荐答案

您可以使用(相当新的) linux syscall renameat2

You can use the (fairly recent) linux syscall renameat2

这是定义:

int renameat2(int olddir, const char *oldname, 
      int newdir, const char *newname, unsigned int flags);

您可以在

You can find its source code on the kernel's Git repo if needed.

它与renameat基本上相同,但是如果传递标志RENAME_EXCHANGE,它将交换两个文件,而不是将一个文件重命名为另一个文件.

It's basically the same as renameat, but if you pass the flag RENAME_EXCHANGE it will swap the two files instead of renaming one into the other.

该操作是原子操作.

这篇关于在Linux上以原子方式交换两个文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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