How to Safely and Transactionally Replace a File on Linux?

好久不见. 提交于 2019-12-23 15:16:48

问题


The most naive, worst way I can think of to replace the contents of a file is:

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

Obviously, if that operation fails at some point before closing, you lose the contents of the original file while not necessarily finishing the new content.

So, what is the completely proper way to do this (if there is one). I imagine it's something like:

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

But is that completely atomic and safe? What are the proper commands to actually perform the move. If I have another process with an open connection to file.txt I assume that it will hold on to its pointer to the original file until is closes. What if another process tries to open up file.txt in the middle of the move?

I don't really care what version of the file my processes get as long as they get a complete, uncorrupted version.


回答1:


Your implementation of move should use the rename function, which is atomic. Processes opening the file will see either the old or the new contents, there is no middle state. If a process already has opened the file it will keep having access to the old version after move.



来源:https://stackoverflow.com/questions/13186263/how-to-safely-and-transactionally-replace-a-file-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!