小智 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)
open 同 O_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与关联任意的fd和ioctl,而当fd关闭时,一切都被释放.
此方法很有用,例如,如果您想要多个file_operations系统调用,但不想创建多个设备文件,这会进一步污染inode:您只需创建额外的fds.
使用QEMU Buildroot的最小可运行示例:
pid 15952
inode 44698689
Run Code Online (Sandbox Code Playgroud)