User`s guide
Shared Memory Between Processes [4]
You can share memory between multiple programs by creating a shared memory
region using the mmap system call.
4.1 Mapping a Memory Region for Data Sharing
A shared memory region is identified by a file name. Before your applications can
use shared memory, you must create an empty readable, writable file and run mmap to
map a memory region to use for shared memory. When you run mmap, it allocates
the specified amount of physical memory and maps it into the caller's address space.
Other programs may share the same memory region by specifying the same file name.
A process may use the unmap system call to unmap the shared memory region.
Example 10. Mapping memory to share among multiple processes
The following example demonstrates how to create a file and map it to a memory
location.
#include <sys/types.h>
#include <sys/mman.h>
#include <stdio.h>
#include <fcntl.h>
#define SHARED_SIZE (256*1024*1024)
int main(int argc, char *argv[])
{
int fd = open(argv[1], O_RDWR|O_CREAT);
if (fd==-1) {
perror(argv[1]);
return 1;
}
caddr_t data = mmap(0, SHARED_SIZE, PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_ANON, fd, 0);
if (data == MAP_FAILED) {
perror("mmap");
return 1;
}
unsigned *words = (unsigned*)data;
// words now points to a shared memory segment
}
S–2479–20 47