重新链接匿名(未链接但打开)文件 [英] Relinking an anonymous (unlinked but open) file

查看:21
本文介绍了重新链接匿名(未链接但打开)文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Unix 中,可以通过以下方式创建匿名文件的句柄,例如,使用 creat() 创建并打开它,然后使用 unlink() 删除目录链接 - 留下一个带有 inode 和存储的文件,但是没有办法重新打开它.此类文件通常用作临时文件(通常这是 tmpfile() 返回给您的内容).

In Unix, it's possible to create a handle to an anonymous file by, e.g., creating and opening it with creat() and then removing the directory link with unlink() - leaving you with a file with an inode and storage but no possible way to re-open it. Such files are often used as temp files (and typically this is what tmpfile() returns to you).

我的问题:有没有办法将这样的文件重新附加到目录结构中?如果你能做到这一点,那就意味着你可以,例如实现文件写入,以便文件以原子方式出现并完全形成.这吸引了我强迫性的整洁.;)

My question: is there any way to re-attach a file like this back into the directory structure? If you could do this it means that you could e.g. implement file writes so that the file appears atomically and fully formed. This appeals to my compulsive neatness. ;)

在查看相关的系统调用函数时,我希望找到一个名为 flink() 的 link() 版本(与 chmod()/fchmod() 相比),但是,至少在 Linux 上它不存在.

When poking through the relevant system call functions I expected to find a version of link() called flink() (compare with chmod()/fchmod()) but, at least on Linux this doesn't exist.

告诉我如何创建匿名文件而无需在磁盘目录结构中简要暴露文件名的奖励积分.

Bonus points for telling me how to create the anonymous file without briefly exposing a filename in the disk's directory structure.

推荐答案

一个补丁几年前提交了一个提议的 Linux flink() 系统调用,但是当 Linus 声明 在没有其他重大入侵的情况下,我们无法安全地做到这一点",这几乎结束了关于是否添加此项的争论.

A patch for a proposed Linux flink() system call was submitted several years ago, but when Linus stated "there is no way in HELL we can do this securely without major other incursions", that pretty much ended the debate on whether to add this.

更新:从 Linux 3.11 开始,现在可以使用 open() 使用新的 O_TMPFILE 标志,并在完全链接到文件系统中使用 linkat() 形成/proc/self/fd/fd 带有 AT_SYMLINK_FOLLOW 标志.

Update: As of Linux 3.11, it is now possible to create a file with no directory entry using open() with the new O_TMPFILE flag, and link it into the filesystem once it is fully formed using linkat() on /proc/self/fd/fd with the AT_SYMLINK_FOLLOW flag.

open() 手册页:

    char path[PATH_MAX];
    fd = open("/path/to/dir", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);

    /* File I/O on 'fd'... */

    snprintf(path, PATH_MAX,  "/proc/self/fd/%d", fd);
    linkat(AT_FDCWD, path, AT_FDCWD, "/path/for/file", AT_SYMLINK_FOLLOW);

请注意,linkat() 将不允许在使用 unlink() 删除最后一个链接后重新附加打开的文件.

Note that linkat() will not allow open files to be re-attached after the last link is removed with unlink().

这篇关于重新链接匿名(未链接但打开)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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