Sharing memory between processes through the use of mmap()

本秂侑毒 提交于 2019-11-28 06:53:48
Maxim Egorushkin

Is it possible to attach that region of memory to the server POST forking, after the client creates it?

MAP_ANONYMOUS|MAP_SHARED mapped memory can only be accessed by the process which does that mmap() call or its child processes. There is no way for another process to map the same memory because that memory can not be referred to from elsewhere since it is anonymous.

Using shm_open() call it is possible to create named shared memory which can be referred to and mapped by unrelated processes.

Just for anyone reading this question in 2018 and later. The solution is now to use memfd_create to create an anonymous file and use a unix socket to pass this file handle to the other process.

memfd_create is a linux only syscall

That's not going to work.

If you create a mapping after the fork(), it won't be the same in the other related process(es).

You can't assume the sharing of pointers in this way.

If you really want to do it this way (I would not recommend it!), you should mmap a big area before the fork(), then allocate somehow, buffers of a suitable size (without race conditions with other processes, of course!) and pass those pointers.

Two related processes which call mmap() after a fork, may get the same pointer back, pointing at different memory. In fact this is extremely likely.

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