shared memory after exec()

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 10:02:02

问题


How can I share memory between the parent and the child if the child has run exec() to load another program?

Is it possible using mmap?

By now parent and child share memory properly using mmap, but not after exec is done


回答1:


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;
}

In the other file:

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;
}

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)




回答2:


How can I share memory between the parent and the child if the child has run exec() to load another program?

Neither memory mappings created via mmap() nor POSIX shared-memory segments obtained via shm_open() nor System V shared-memory segments obtained via shmat() are preserved across an exec. That covers all the forms of shared memory I am aware of Linux providing.

It follows that if you want the child to share memory with the parent after an exec() then the child must (re)connect to the appropriate shared memory after the exec(). Obviously, that means that whatever program is started by the exec() must be written to do that. (Note in particular that on success, the exec-family functions do not return.)

Is it possible using mmap?

Only if the child re-maps the memory after the exec().

By now parent and child share memory properly using mmap, but not after exec is done

That is by design.



来源:https://stackoverflow.com/questions/48190685/shared-memory-after-exec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!