以原子方式将文件替换为另一个文件的硬链接

发布于 2024-08-27 20:24:40 字数 354 浏览 6 评论 0原文

我有两个目录条目,a 和 b。 之前,a和b指向不同的inode。 之后,我希望 b 指向与 a 相同的 inode。 我希望这是安全的 - 我的意思是如果我在某个地方失败,b 要么指向其原始 inode,要么指向 a inode。最特别的是我不想最终 b 消失。

mv 覆盖时是原子的。

当目标已经存在时 ln 似乎不起作用。

所以看起来我可以说:

ln a tmp mv tmp b

如果发生故障,将会留下一个“tmp”文件,这是不可取的,但也不是灾难。

有更好的方法吗?

(我实际上想做的是将具有相同内容的文件替换为包含该内容的单个 inode,在所有目录条目之间共享)

I have two directory entries, a and b.
Before, a and b point to different inodes.
Afterwards, I want b to point to the same inode as a does.
I want this to be safe - by which I mean if I fail somewhere, b either points to its original inode or the a inode. most especially I don't want to end up with b disappearing.

mv is atomic when overwriting.

ln appears to not work when the destination already exists.

so it looks like i can say:

ln a tmp
mv tmp b

which in case of failure will leave a 'tmp' file around, which is undesirable but not a disaster.

Is there a better way to do this?

(what I'm actually trying to do is replace files that have identical content with a single inode containing that content, shared between all directory entries)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

原谅我要高飞 2024-09-03 20:24:40

ln a tmp && mv tmp b || rm tmp

似乎更好,因为如果 ln 失败,则 mv 将不会被执行(并且在失败时使 stderr 变得混乱)。

ln a tmp && mv tmp b || rm tmp

seems better, as then if ln fails, the mv will not get executed (and clutter up stderr when it fails).

蓬勃野心 2024-09-03 20:24:40
 ln a tmp ; mv tmp b

事实上,正如您在问题中所述,这是原子地执行此操作的最快方法。

(挑剔者角落:更快地将两个系统调用放在一个程序中)

 ln a tmp ; mv tmp b

is in fact the fastest way to do it atomically, as you stated in your question.

(Nitpickers corner: faster to place both system calls in one program)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文