antonone antonone - 1 year ago 89
Linux Question

Atomically swap contents of two files on Linux

I have two files,

, each with its own content.

I would like to swap these two files, so
would become
, and
would become
. 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).

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

Answer Source

You can use the (fairly recent) linux syscall renameat2

Here is the definition :

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.

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.

The operation is atomic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download