views:

1598

answers:

3

Needing to use IPC to pass large-ish amounts of data (200kb+) from a child process to a parent on OS X 10.4 and above, I read up on shared memory on Unix, specifically System V and POSIX shared memory mechanisms. Then I realized that mmap() can be used with the MAP_ANON and MAP_SHARED flags to do a similar thing (or just with the MAP_SHARED flag, if I don't mind a regular file being created).

My question is, is there any reason not to just use mmap()? It seems much simpler, the memory is still shared, and it doesn't have to create a real file if I use MAP_ANON. I can create the file in the parent process then fork() and exec() the child and use it in the child process.

Second part of the question is, what would be reasons that this approach is not sufficient, and one would have to use SysV or POSIX shared memory mechanisms?

Note that I was planning on doing synchronization using pipes that I need for other communication, i.e. the parent asks for data over the pipe, the child writes it to shared memory, and responds over the pipe that its ready. No multiple readers or writers involved. Portability is not a priority.

A: 

If memory serves, the only reason to use SysV/POSIX over mmap is portability. In particularly older Unix systems don't support MAP_ANON. Solaris, Linux, the BSDs and OS X do, however, so in practice, there's little reason not to use mmap.

Michiel Buddingh'
A: 

shm in Linux is typically implemented via a /dev/shm file that gets mmapped, so, performance should be equivalent -- I'd go with mmap (w/MAP_ANON and MAP_SHARED as you mention) for simplicity, if I know portability is no issue as you say's the case for you.

Alex Martelli
+2  A: 

If you have a parent/child relationship, it's perfectly fine to use mmap.

sysv_shm is the original unix implementation that allows related and unrelated processes to share memory. posix_shm standardized shared memory.

If you're on posix system without mmap, you'd use posix_shm. If you're on a unix without posix_shm you'd use sysv_shm. If you only need to share memory vs a parent/child you'd use mmap if available.

nos
Ah, yes. That answers both questions, and I should have realized that. Similar to the reason to use named pipes if you already have pipes. Thanks!
Bob