I have a linux embedded environment.
Here I have 2 scenarios:
A:
Result: After reboot, what I have is:
B:
Open and write a temporary file.
FSYNC temporary file.
Rename temporary file to the original file.
Power loss
Result: After reboot,
As you see, between these 2 scenarios, the only difference is fsync of temporary file, and not the original file. In both, I did not fsync the original file.
So, why the original content of original file is kept in scenario B?
From point of view of original file, the change is, actualizing it by renaming non-fsynced file vs fsynced file.
How does this keep the original content?
Edit:
This scenario actualizing original file also failed to safely actualize original file:
Open and write a temporary file.
FSYNC temporary file.
Rename temporary file to the original file.
Fsync original file's directory
Power loss
Result:
0-size original file.
So, how should I do that?
Normaly, if you want to be immune to a power loss, you use journaling. That means that (broadly speaking) you store what you want to write and where, you write it, and when it as successfully be written, you remove it (at least logically) from the journal. In case of major failure (power loss or other system crash), you read the journal and apply any changes still presend. Many file systems have options to enable it, and on a journaling file system, you can expect a rename to be atomic and immune to a power loss: the file will exist either under its previous or new name.
So the common workflow is:
In case of power loss (or any other crash condition), on next reboot things are simple: