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

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

问题描述

在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()的链接()(与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.

奖励积分,告诉我如何创建匿名文件,而不会在磁盘的目录结构中短暂显示文件名。 / p>

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表示HELL中没有办法,我们可以安全地执行,而无需其他的其他入侵,几乎结束了辩论是否添加这个。

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开始,现在可以使用 O_TMPFILE 的n-pages / man2 / open.2.htmlrel =noreferrer> open() code>标志,并使用 / proc / self / fd / fd linkat() > 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() 手册页:

The following example is provided on the open() manual page:

    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天全站免登陆