在Linux上以原子方式交换两个文件的内容
我有两个文件A
和B
,每个文件都有自己的内容.
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.
该操作是原子操作.