共享内存模型:
- memory-mapped file,一个特殊的文件,用于被不同进程获取同一块关联的内存区域
- shared-memory object,在代码中表示为一个指针,指向这块共享的内存区域
Producer: Consumer:代码实例
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main() {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char *name = "OS";
/* strings written to shared memory */
const char *message 0 = "Hello";
const char *message 1 = "World!";
/* shared memory file descriptor */
int fd;
/* pointer to shared memory obect */
char *ptr;
/* create the shared memory object */
fd = shm_open(name, O CREAT | O RDWR, 0666);
/* configure the size of the shared memory object */
ftruncate(fd, SIZE);
/* memory map the shared memory object */
ptr = (char *)mmap(0, SIZE, PROT READ | PROT WRITE, MAP SHARED, fd, 0);
/* write to the shared memory object */
sprintf(ptr, "%s", message 0);
ptr += strlen(message 0);
sprintf(ptr, "%s", message 1);
ptr += strlen(message 1);
return 0;
}
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main() {
/* the size (in bytes) of shared memory object */
const int SIZE = 4096;
/* name of the shared memory object */
const char *name = "OS";
/* shared memory file descriptor */
int fd;
/* pointer to shared memory obect */
char *ptr;
/* open the shared memory object */
fd = shm_open(name, O RDONLY, 0666);
/* memory map the shared memory object */
ptr = (char *)mmap(0, SIZE, PROT READ | PROT WRITE, MAP SHARED, fd, 0);
/* read from the shared memory object */
printf("%s", (char *)ptr);
/* remove the shared memory object */
shm_unlink(name);
return 0;
}