名詞定義:
shm-posix-producer.c
/**
* Simple program demonstrating shared memory in POSIX systems.
*
* This is the producer process that writes to the shared memory region.
*
* Figure 3.17
*
* @author Silberschatz, Galvin, and Gagne
* Operating System Concepts - Ninth Edition
* Copyright John Wiley & Sons - 2013
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main()
{
const int SIZE = 4096; /* 定義共享記憶體的大小為 4096 bytes */
const char *name = "OS"; /* 定義共享記憶體段的名稱 */
const char *message0= "Studying ";
const char *message1= "Operating Systems ";
const char *message2= "Is Fun!";
int shm_fd; /* 儲存共享記憶體段的檔案描述符 */
void *ptr; /* 用於儲存映射區域的指標 */
/* create the shared memory segment */
/* 創建或打開一個共享記憶體段,名稱為 "OS",具有讀寫權限 */
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
/* configure the size of the shared memory segment */
/* 設置共享記憶體段的大小為 4096 bytes */
ftruncate(shm_fd,SIZE);
/* now map the shared memory segment in the address space of the process */
/* 將共享記憶體段映射到進程的地址空間,允許讀寫 */
ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
/* 如果映射失敗,打印錯誤信息並返回 -1 */
if (ptr == MAP_FAILED) {
printf("Map failed\n");
return -1;
}
/**
* Now write to the shared memory region.
*
* Note we must increment the value of ptr after each write.
*/
sprintf(ptr,"%s",message0); /* 將 message0 寫入共享記憶體 */
ptr += strlen(message0); /* 更新指標位置 */
sprintf(ptr,"%s",message1);
ptr += strlen(message1);
sprintf(ptr,"%s",message2);
ptr += strlen(message2);
return 0;
}
shm-posix-consumer.c
/**
* Simple program demonstrating shared memory in POSIX systems.
*
* This is the consumer process
*
* Figure 3.18
*
* @author Gagne, Galvin, Silberschatz
* Operating System Concepts - Ninth Edition
* Copyright John Wiley & Sons - 2013
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main()
{
const char *name = "OS";
const int SIZE = 4096;
int shm_fd;
void *ptr;
int i;
/* open the shared memory segment */
/* 以只讀方式打開共享記憶體段 */
shm_fd = shm_open(name, O_RDONLY, 0666);
/* 如果打開失敗,打印錯誤信息並退出程式 */
if (shm_fd == -1) {
printf("shared memory failed\n");
exit(-1);
}
/* now map the shared memory segment in the address space of the process */
/* 將共享記憶體段映射到進程的地址空間,允許讀取 */
ptr = mmap(0,SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
/* 如果映射失敗,打印錯誤信息並退出程式 */
if (ptr == MAP_FAILED) {
printf("Map failed\n");
exit(-1);
}
/* now read from the shared memory region */
/* 從共享記憶體中讀取資料並打印到標準輸出 */
printf("%s",ptr);
/* remove the shared memory segment */
/* 刪除共享記憶體段,如果失敗則打印錯誤信息並退出程式 */
if (shm_unlink(name) == -1) {
printf("Error removing %s\n",name);
exit(-1);
}
return 0;
}
Terminal
編譯並執行
gcc -o shm-posix-producer shm-posix-producer.c
gcc -o shm-posix-consumer shm-posix-consumer.c
./shm-posix-producer
./shm-posix-consumer
結果:
參考: