Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
695 views
in Technique[技术] by (71.8m points)

c - Linux shared memory: shmget() vs 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().

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Some hints:

  • If you create your children via fork then mmap with MAP_ANONYMOUS | MAP_SHARED is by far the easiest way - just one call. MAP_ANONYMOUS is however a Linux extension not specified by POSIX.
  • If you start the processes independently, but can supply them with a shared memory name then shm_open (+ ftruncate) + mmap with MAP_SHARED is two/three calls. Requires librt on some OSes.
  • If your OS has /dev/shm/ then shm_open is equivalent to opening a file in /dev/shm/.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...