文档介绍:利用共享内存进行进程同步
实验目的
理解 Linux 关于共享内存的概念,掌握 Linux 支持进程间内存共享的系统调用。
巩固掌握进程同步概念。
实验内容
使用共享内存来完成进程间通信。
要求建立一个利用共享内存机制的,关于经典同步问题 readers/writers 的解决方案。
writer 从用户处获得输入,然后将其写入共享内存,reader 从共享内存获取信息,然后再在
屏幕上打印出来。
实验提示
一、关于共享内存的系统调用
让我们看一个简单的例子程序,从中体会共享内存系统调用函数的使用。
这个程序首先调用 shmget()函数建立一块共享内存,大小为 1024 个字节,该函数返
回创建的共享内存的标识符。
然后 fork 一个子进程,子进程调用 shmat()函数将该共享内存连接(attach)到自己
的虚存空间,即可通过普通的内存写操作(例如 strcpy 等),在该共享内存写入一个字符串,
然后调用 shmdt()函数断开(detach)与该共享内存的连接。
在这段时间里,父进程 sleep,等待子进程完成上述操作,然后调用 shmctl()函数得
到关于这块共享内存的相关信息,并打印出来。然后调用 shmat()函数将这块共享内存连
接(attach)到自己的虚存空间,即可通过普通的内存读操作(例如 printf 等),将该共享
内存中的字符串读出来。最后,调用 shmctl()函数,销毁该共享内存。
/******** 一个简单的使用共享内存的例子***************/
#include <>
#include <sys/>
#include <sys/>
#include <>
#define KEY 1234 /* 键*/
#define SIZE 1024 /* 欲建立的共享内存的大小*/
int main(){
int shmid;
char *shmaddr;
struct shmid_ds buf;
shmid = shmget(KEY,SIZE,IPC_CREAT|0600); /* 建立共享内存*/
if(shmid == -1){
printf("create share memory failed: %s",strerror(errno));
return 0;
}
if(fork() == 0){ /* 子进程*/
/* 系统自动选择一个地址连接*/
shmaddr = (char *)shmat(shmid,NULL,0);
if(shmaddr == (void *)-1){
printf("connect to the share memory failed: %s",strerror(errno));
return 0;
}
strcpy(shmaddr,"hello, this is child process!\n");
shmdt(shmaddr); /* detach 共享内存*/
return 0;
}else{ /* 父进程*/
sleep(3); /* 等待子进程执行完毕*/
shmctl(shmid,IPC_STAT,&buf); /* 取得共享内存的相关信息*/
printf(" size of the share memory: ");
printf("shm_segsz = %d bytes \n",);
printf(" process id of the creator: ");
printf("shm_cpid = %d \n",);
printf(" process id of the last operator: ");
printf("shm_lpid = %d \n",);
/* 系统自动选择一个地址连接*/
shmaddr = (char *)shmat(shmid,NULL,0);
if(shmaddr == (void *)-1){
printf("connect the share memory failed: %s",strerror(errno));
return 0;
}