如何安全地和事务性地替换Linux上的文件? [英] How to Safely and Transactionally Replace a File on Linux?

查看:154
本文介绍了如何安全地和事务性地替换Linux上的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  f = open(

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

显然,如果这个操作在关闭之前的某个时候失败了,那么您将丢失原始文件的内容,而不一定会完成新内容。



那么,完全正确的方法是什么(如果有的话)。我想像是这样的:

$ p $ f = open('file.txt.tmp','w')
f.write('stuff')
f.close()
move('file.txt.tmp','file.txt')#危险线?

但这是完全原子性和安全性的吗?什么是真正执行移动的正确命令。如果我有一个打开连接到 file.txt 的另一个进程,我认为它将保持其指向原始文件的指针,直到关闭。如果另一个进程试图在移动过程中打开 file.txt



真正关心我的进程得到一个完整的,没有损坏的版本文件的版本。 move 应该使用原子的 rename 函数。打开文件的过程将看到旧的或新的内容,没有中间状态。如果一个进程已经打开这个文件,它将继续访问 move 之后的旧版本。


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.

解决方案

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.

这篇关于如何安全地和事务性地替换Linux上的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆