使用硬链接(hard link)的 Python 写时复制

标签 python unix hardlink

使用 Python 2.5+,UNIX:

我有一个程序通过硬链接(hard link)所有条目来模拟目录“写时复制”功能。目前所有底层代码,其中一些我无法访问,都使用标准的 open(fname, 'w') 来编写常规文件。

但是对于硬链接(hard link),这意味着使用了相同的 inode(只是被截断了),因此原始内容也被破坏了。对于写时复制,我当然希望原件保持不变(旧 inode)并且 open('w') 调用创建一个新 inode。

关于实现此目标的最佳方法有什么想法吗?猴子补丁 open 不知何故?

到目前为止,我想到的是重写 open 以尝试先删除文件(如果它存在),然后才执行 open('w'):

import __builtin__
_open = __builtin__.open

def my_open(name, mode='r', *args, **kwargs):
    """Simulate copy-on-write, by deleting the file first if it exists"""
    if 'w' in mode and os.path.exists(name): # TODO: use isfile()?
        os.remove(name)
    return _open(name, mode, *args, **kwargs)

__builtin__.open = my_open

最佳答案

你在找这样的东西吗?

import sys
old_open = __builtins__.open    

# Override builtin open()
def my_open(fname, *args, **kwargs):
    # If the path is a hardlink, (ie, check that st_nlink >1)
    if os.path.isfile(fname) and os.stat(fname).st_nlink > 1: 
        os.unlink(fname)
    return old_open(fname, *args, **kwargs)
__buitlins__.open = my_open

关于使用硬链接(hard link)的 Python 写时复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9924886/

相关文章:

linux - 创建期间的 Unix 文件权限

linux - 如何确定运行 rm -rf 时释放的空间量

python - 从列表中查找最接近的坐标对

python - 使用绑定(bind)时 cx_Oracle 返回空查询

python - 如何取消选择pydatatable中特定索引处的行?

c++ - 检测内存泄漏的工具

python - 在 Python 中覆盖 "+="? (__iadd__() 方法)

c - C套接字中奇怪的while循环?

c - 如何使用 lstat() 来确定是否有硬链接(hard link)

linux - 是否有用于创建硬链接(hard link)备份的实用程序?