Search code examples
clinuxatomicfwrite

using fwrite as an atomic process on Linux


I am developing a C code on Linux environment. I use fwrite to write some data to some files. The program will be run on an environment that power cut offs occur often (at least once a day). Therefore, I want fwrite to ensure that the file should not be updated if a power cut occurs while it is writing data. It should only save the file when the fwrite finishes its job. How can I use fwrite that effects the file only it finishes the writing process?

EDIT: I use fopen with wb to discard the previous info in the file and write a new file e.g.

FILE *rtng_p;
rtng_p = fopen("/etc/routing_table", "wb");
fwrite(&user_list, sizeof(struct routing), 40, rtng_p);

and it is a very small data some bytes long


Solution

  • First write the file to a temporary path on the same filesystem, like /etc/routing_table.tmp. Then just rename the copy on top of original file. Renames are guaranteed atomic.

    So, the sequence of calls would be, fopen, fwrite, fclose, rename.