如果指向的文件被移动或删除,Linux 上打开的文件句柄会发生什么 [英] What happens to an open file handle on Linux if the pointed file gets moved or deleted

查看:59
本文介绍了如果指向的文件被移动或删除,Linux 上打开的文件句柄会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果同时获取指向的文件,Linux 上打开的文件句柄会发生什么:

What happens to an open file handle on Linux if the pointed file meanwhile gets:

  • 搬走 -> 文件句柄是否保持有效?
  • 已删除 -> 这是否会导致 EBADF,表明文件句柄无效?
  • 被新文件替换 -> 文件句柄是否指向这个新文件?
  • 被一个新文件的硬链接替换 ​​-> 我的文件是否处理跟随"这个链接?
  • 被一个新文件的软链接替换 ​​-> 我的文件句柄现在是否命中了这个软链接文件?

我为什么要问这样的问题:我使用的是热插拔硬件(例如 USB 设备等).设备(及其/dev/file)可能会被用户或其他 Gremlin 重新连接.

Why I'm asking such questions: I'm using hot-plugged hardware (such as USB devices etc.). It can happen, that the device (and also its /dev/file) gets reattached by the user or another Gremlin.

处理这个问题的最佳做法是什么?

What's the best practice dealing with this?

推荐答案

如果文件被移动(在同一个文件系统中)或重命名,则文件句柄保持打开状态,仍可用于读取和写入文件.

If the file is moved (in the same filesystem) or renamed, then the file handle remains open and can still be used to read and write the file.

如果文件被删除,文件句柄保持打开状态,仍然可以使用(这不是一些人所期望的).直到最后一个句柄关闭,文件才会真正被删除.

If the file is deleted, the file handle remains open and can still be used (This is not what some people expect). The file will not really be deleted until the last handle is closed.

如果文件被新文件替换,则取决于具体如何替换.如果文件的内容被覆盖,文件句柄仍然有效并访问新内容.如果现有文件已取消链接并使用相同名称创建了一个新文件,或者,如果使用 rename() 将新文件移动到现有文件上,则与删除相同(见上文)-也就是说,文件句柄将继续引用文件的原始版本.

If the file is replaced by a new file, it depends exactly how. If the file's contents are overwritten, the file handle will still be valid and access the new content. If the existing file is unlinked and a new one created with the same name or, if a new file is moved onto the existing file using rename(), it's the same as deletion (see above) - that is, the file handle will continue to refer to the original version of the file.

一般来说,一旦文件被打开,文件就会被打开,任何改变目录结构的人都不能改变这一点——他们可以移动、重命名文件,或者在它的位置放置其他东西,它只是保持打开状态.

In general, once the file is open, the file is open, and nobody changing the directory structure can change that - they can move, rename the file, or put something else in its place, it simply remains open.

在 Unix 中没有删除,只有 unlink(),这是有道理的,因为它不一定删除文件 - 只是从目录中删除链接.

In Unix there is no delete, only unlink(), which makes sense as it doesn't necessarily delete the file - just removes the link from the directory.

另一方面,如果底层设备消失(例如 USB 拔出),则文件句柄将不再有效,并且可能会在任何操作中产生 IO/错误.尽管如此,您仍然必须关闭它.即使重新插入设备也是如此,因为在这种情况下保持文件打开是不明智的.

If on the other hand the underlying device disappears (e.g. USB unplug) then the file handle won't be valid any more and is likely to give IO/error on any operation. You still have to close it though. This is going to be true even if the device is plugged back in, as it's not sensible to keep a file open in this case.

这篇关于如果指向的文件被移动或删除,Linux 上打开的文件句柄会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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