memfd_create提供了一个方法,可以在内存中创建一个匿名文件,但是这个文件在真实的文件系统中却不存在。
#define _GNU_SOURCE
#include <sys/mman.h>
int memfd_create(const char *name, unsigned int flags);
参数:
name:文件的名字
flags:常用参数为MFD_CLOEXEC,在调用execv时会自动关闭
#include <sys/mman.h>
#include <unistd.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
int fd = memfd_create("mem_file", 0);
if(fd < 0)
{
cout << "memfd_create failed" << endl;
return -1;
}
cout << "create fd:" << fd <<endl;
string s = "hello";
write(fd, s.c_str(), s.length());
char buf[100] = {0};
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
cout << "read from file:" <&l