exec()之后的共享内存 [英] shared memory after exec()
问题描述
如果孩子已经运行 exec()来加载另一个程序,如何在父母和孩子之间共享内存?
How can I share memory between the parent and the child if the child has run exec() to load another program?
是否可以使用 mmap ?
现在,父母和孩子可以使用mmap正确共享内存,但是在完成 exec 之后不能这样做
By now parent and child share memory properly using mmap, but not after exec is done
推荐答案
您可以使用shm_open
打开由文件系统上的文件标识的命名"共享内存块.例子:
在父项中:
You can use shm_open
to open a "named" shared memory block which is identified by a file on the filesystem. Example:
In the parent:
int memFd = shm_open("example_memory", O_CREAT | O_RDWR, S_IRWXU);
if (memFd == -1)
{
perror("Can't open file");
return 1;
}
int res = ftruncate(memFd, /*size of the memory block you want*/);
if (res == -1)
{
perror("Can't truncate file");
return res;
}
void *buffer = mmap(NULL, /*size of the memory block you want*/, PROT_READ | PROT_WRITE, MAP_SHARED, memFd, 0);
if (buffer == NULL)
{
perror("Can't mmap");
return -1;
}
在另一个文件中:
int memFd = shm_open("example_memory", O_RDONLY, 0);
if (memFd == -1)
{
perror("Can't open file");
return 1;
}
void *buffer = mmap(NULL, /*size of the memory block you want*/, PROT_READ, MAP_SHARED, memFd, 0);
if (buffer == NULL)
{
perror("Can't mmap");
return -1;
}
这些代码段之后,您可以使用buffer
访问共享内存. (注意:它不必为void*
,您可以使其成为指向要存储在共享内存中的任何内容的指针)
After these segments of code you can use buffer
to access the shared memory. (Note: it doesn't need to be void*
, you can make it a pointer to whatever you intend to store in the shared mem)
这篇关于exec()之后的共享内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!