Linux中的匿名inode是什么?

mrk*_*han 20 linux inode epoll

我做了一个关于"匿名inode"的谷歌搜索,它似乎与epoll有关......但究竟是什么呢?

小智 19

至少在某些情况下,匿名inode是没有附加目录条目的inode.创建此类inode的最简单方法是:

int fd = open( "/tmp/file", O_CREAT | O_RDWR, 0666 );
unlink( "/tmp/file" );
// Note that the descriptor fd now points to an inode that has no filesystem entry; you
// can still write to it, fstat() it, etc. but you can't find it in the filesystem.
Run Code Online (Sandbox Code Playgroud)

  • 不,它是磁盘上的数据,但该数据在文件系统中没有可以打开的条目 - 您只能使用数据,直到打开的最后一个文件描述符关闭.您需要这种情况的一种情况是,您需要一个不希望任何人能够打开的临时文件; UNIX中mktemp()调用的许多用法实际上是您不希望其他进程能够打开文件的情况,您只需要出于某种原因需要临时文件. (9认同)
  • 有没有办法重新链接目录条目? (2认同)
  • 不,这样的文件不能重新链接。 (2认同)

Cir*_*四事件 6

openO_TMPFILE

这将是匿名inode的一个很好的定义:它在给定目录中创建一个没有任何名称的inode,它根本不会出现ls.

然后,当您关闭描述符时,文件将被删除.

它是在Linux 3.11中添加的.

#define _GNU_SOURCE
#include <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    char buf[]  = { 'a', 'b', 'c', 'd' };
    char buf2[]  = { 'e', 'f', 'g', 'h' };
    int f, ret;
    size_t off;

    /* write */
    f = open(".", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
    ret = write(f, buf, sizeof(buf));

    /* Interactivelly check if anything changed on directory. It hasn't. */
    /*puts("hit enter to continue");*/
    /*getchar();*/

    /* read */
    lseek(f, 0, SEEK_SET);
    off = 0;
    while ((ret = read(f, buf2 + off, sizeof(buf) - off))) {
        off += ret;
    }
    close(f);
    assert(!memcmp(buf, buf2, sizeof(buf)));

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

在Ubuntu 17.04,Linux 4.10,glibc 2.24中测试,运行:

gcc -o main.out -std=c99 -Wall -Wextra -pedantic  main.c
./main.out
Run Code Online (Sandbox Code Playgroud)

O_TMPFILE Linux内核功能

如果您正在处理内核模块,这可能是一个定义.

你称之为:

#define _GNU_SOURCE
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(void) {
    int f = open(".", O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR);
    struct stat s;
    fstat(f, &s);
    printf("pid %jd\n", (intmax_t)getpid());
    printf("inode %jd\n", (intmax_t)s.st_ino);
    getchar();
}
Run Code Online (Sandbox Code Playgroud)

并返回/proc/PID/fd用户,例如来自inode.

现在用户有一个anon_inode_getfd与关联任意的fdioctl,而当fd关闭时,一切都被释放.

此方法很有用,例如,如果您想要多个file_operations系统调用,但不想创建多个设备文件,这会进一步污染inode:您只需创建额外的fds.

使用QEMU Buildroot的最小可运行示例:

pid 15952     
inode 44698689
Run Code Online (Sandbox Code Playgroud)