Linux共享内存:shmget的()与mmap()的? [英] Linux shared memory: shmget() vs mmap()?
问题描述
在这线程的OP建议使用的mmap()
而不是中的shmget()
在Linux中得到共享内存。
我参观了这个页面和<一个href=\"http://www.jims$c$c.ca/index.php/component/content/article/13-c/45-c-simple-mmap-example\">this页面来获得一些文件,但第二个方面给出了一个模糊的例子的mmap()
。
In this thread the OP is suggested to use mmap()
instead of shmget()
to get shared memory in Linux.
I visited this page and this page to get some documentation, but the second one gives an obscure example regarding mmap()
.
作为几乎是一个新手,并且需要两个进程之间共享一些信息(以文本形式),我应该使用 shmget的()
方法或 mmap()的
?为什么?
Being almost a newbie, and needing to share some information (in text form) between two processes, should I use the shmget()
method or mmap()
? And why?
感谢您,
鲍勃
推荐答案
这两种方法都是可行的。 MMAP
方法是更严格的那么一点点 shmget的
,但更容易使用。 shmget的
是旧的System V共享内存模式,并具有最广泛的支持。 MMAP
/ 的shm_open
是新的POSIX的方式做共享内存和更容易使用。如果您的操作系统允许使用POSIX共享内存的话,我会建议与去。
Both methods are viable. mmap
method is a little bit more restrictive then shmget
, but easier to use. shmget
is the old System V shared memory model and has the widest support. mmap
/shm_open
is the new POSIX way to do shared memory and is easier to use. If your OS permits the use of POSIX shared memory then I would suggest going with that.
一些提示:
- 如果您通过
叉
然后MMAP
与MAP_ANONYMOUS创建您的孩子| MAP_SHARED
是迄今为止最简单的方式 - 只需一个电话 - 如果您单独启动过程,但可以用一个共享内存名给他们,那么
的shm_open
(+ftruncate
)+MMAP
与MAP_SHARED
是二/三个电话。需要librt
在一些操作系统。 - 如果您的操作系统有
的/ dev / shm的/
然后的shm_open
等同于<$ C打开一个文件$ C>的/ dev / shm的/ 。
- If you create your children via
fork
thenmmap
withMAP_ANONYMOUS | MAP_SHARED
is by far the easiest way - just one call. - If you start the processes independently, but can supply them with a shared memory name then
shm_open
(+ftruncate
) +mmap
withMAP_SHARED
is two/three calls. Requireslibrt
on some OSes. - If your OS has
/dev/shm/
thenshm_open
is equivalent to opening a file in/dev/shm/
.
这篇关于Linux共享内存:shmget的()与mmap()的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!