2

I've some c application under linux. I'm renaming some files with rename(...) How can I ensure that the renaming is written persistent to the underlaying disk?

With a file I can do something like:

FILE * f = fopen("foo","w");
...
fflush(f);
fsync(fileno(f));
fclose(f);

How can I fsync (or similar) a directory after a rename() in c?

powerpete
  • 2,663
  • 2
  • 23
  • 49

3 Answers3

3

This is how you can do what you want:

#include <fcntl.h>
int fd = open('/path/to/dir', O_RDONLY);
fsync(fd);

Don't forget to close the fd file descriptor when no longer needed of course.

Contrary to some misconceptions, the atomicity of rename() does not guarantee the file will be persisted to disk. The atomicity guarantee only ensures that the metadata in the file system buffers is in a consistent state but not that it has been persisted to disk.

hetman
  • 919
  • 6
  • 16
1

rename() is atomic (on linux), so I don't think you need to worry about that

Atomicity is typically guaranteed in operations involving filename handling ; for example, for rename, “specification requires that the action of the function be atomic” – that is, when renaming a file from the old name to the new one, at no circumstances should you ever see the two files at the same time.

a power outage in the middle of a rename() operation shall not leave the filesystem in a “weird” state, with the filename being unreachable because its metadata has been corrupted. (ie. either the operation is lost, or the operation is committed.)

Source

So, I think you should only be worried about error value.


If you really want to be safe, fsync() also flush metadata (on linux), so you could fsync the directory and the file you want to be sure there are present on the disk.

Community
  • 1
  • 1
Stargateur
  • 24,473
  • 8
  • 65
  • 91
-2

According to the manual, at the return of the function, rename has been done effectively (return 0) or an error occured (return -1) and errno is set to check what's wrong.

If you want the system to apply the potential pending modifications only on this file after rename you can do :

int fd = open(new_name, O_RDONLY);
syncfs(fd);
Paul Ankman
  • 190
  • 9