How to safely and transactionally replace a file on Linux?

The most naive, worst way to replace the contents of a file:

f = open('file.txt', 'w') f.write('stuff') f.close() 

Obviously, if this operation fails at some point before closing, you will lose the contents of the original file, not necessarily ending with new content.

So what is the perfectly correct way to do this (if any). I imagine something like:

 f = open('file.txt.tmp', 'w') f.write('stuff') f.close() move('file.txt.tmp', 'file.txt') # dangerous line? 

But is it completely atomic and safe? What are the right commands to actually execute the movement. If I have another process with an open connection to file.txt , I assume that it will hold the pointer to the source file until it is closed. What if another process tries to open file.txt in the middle of a move?

I don't care what version of the file my processes have, as long as they get the full, undamaged version.

+4
source share
1 answer

Your implementation of move should use the rename function, which is atomic. The processes that open the file will see either the old or the new content, there is no average state. If the process has already opened the file, it will have access to the old version after move .

+4
source

Source: https://habr.com/ru/post/1443543/


All Articles