I want to write some lines to a file, and I need each line of writing is a atomic operation.
For example, I have 3 lines:
111111111111111111111111
222222222222222222222222
333333333333333333333333
When I write them into a file line by line, the program may be exit by error, so the saved data may be:
11111111111111111111111
222222
This is not what I expected. I hope each line is a transaction, a atomic operation.
How should I do this?
Currently I use Java to do this.
There isn’t a 100% reliable way to guarantee this.
I think the closest you can get is by calling
flush()on the output stream and thensync()on the underlying file descriptor. Again, there are failure modes where this won’t help.