原子地移动目录 [英] Moving a directory atomically

查看:27
本文介绍了原子地移动目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一个父目录中有两个目录.调用父目录 base 和子目录 alphabravo.我想用 bravo 替换 alpha.最简单的方法是:

I have two directories in the same parent directory. Call the parent directory base and the children directories alpha and bravo. I want to replace alpha with bravo. The simplest method is:

rm -rf alpha
mv bravo alpha

mv 命令是原子的,但 rm -rf 不是.bash 中是否有一种简单的方法可以将 alpha 原子替换为 bravo?如果没有,有没有复杂的方法?

The mv command is atomic, but the rm -rf is not. Is there a simple way in bash to atomically replace alpha with bravo? If not, is there a complicated way?

附录:

顺便说一下,如果目录在短时间内不存在,这不是一个无法解决的问题.只有一个地方会尝试访问 alpha,它会在执行任何关键操作之前检查 alpha 是否存在.如果没有,它会给出错误消息.但如果有办法做到这一点就好了.:) 也许有一些方法可以直接修改 inode,或者其他什么...

By the by, it's not an insurmountable problem if the directory doesn't exist for a short period. There's only one place that tries to access alpha, and it checks if alpha exists before doing anything critical. If not, it gives an error message. But it would be nice if there was a way to do this. :) Maybe there's some way to modify the inodes directly, or something...

推荐答案

如果你使用符号链接,你可以这样做:

You can do this if you use symlinks:

假设 alpha 是指向 alpha_1 目录的符号链接,并且您希望将符号链接切换为指向 alpha_2.这是切换前的样子:

Let's say alpha is a symlink to directory alpha_1, and you want to switch the symlink to point to alpha_2. Here's what that looks like before the switch:

$ ls -l
lrwxrwxrwx alpha -> alpha_1
drwxr-xr-x alpha_1
drwxr-xr-x alpha_2

要使 alpha 引用 alpha_2,请使用 ln -nsf:

To make alpha refer to alpha_2, use ln -nsf:

$ ln -nsf alpha_2 alpha
$ ls -l
lrwxrwxrwx alpha -> alpha_2
drwxr-xr-x alpha_1
drwxr-xr-x alpha_2

现在您可以删除旧目录:

Now you can remove the old directory:

$ rm -rf alpha_1

请注意,这实际上不是一个完全原子的操作,但它确实发生得非常快,因为ln"命令既取消链接又立即重新创建符号链接.您可以使用 strace 验证此行为:

Note that this is NOT actually a fully atomic operation, but it does happen very quickly since the "ln" command both unlinks and then immediately recreates the symlink. You can verify this behaviour with strace:

$ strace ln -nsf alpha_2 alpha
...
symlink("alpha_2", "alpha")             = -1 EEXIST (File exists)
unlink("alpha")                         = 0
symlink("alpha_2", "alpha")             = 0
...

您可以根据需要重复此过程:例如当您有新版本时,alpha_3:

You can repeat this procedure as desired: e.g. when you have a new version, alpha_3:

$ ln -nsf alpha_3 alpha
$ rm -rf alpha_2

这篇关于原子地移动目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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