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

问题描述

我有相同的父目录两个目录。调用父目录的基础和孩子们的目录字母布拉沃。我想替换字母布拉沃。最简单的方法是:

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命令是原子,但室射频不大。有一个简单的方法在bash以原子取代的字母布拉沃?如果没有,是否有一个复杂的方式?

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?

附录:

靠了靠,这不是一个不可逾越的问题,如果该目录不很短的时间存在。这里只有一个试图访问阿尔法的地方,它会检查是否阿尔法做任何事情之前,关键存在。如果不是,它提供了一个错误消息。但是,如果有办法做到这一点就好了。 :)也许有一些方法来直接修改的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_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

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

10-12 15:43