使用共享存储区的示例程序
下面程序主要用来演示共享存储区的使用方法:首先要使用shmget得到共享存储区句柄(可以新建或连接已有的共享存储区,以关键字标识),然后使用shmat挂接到进程的存储空间(这样才能够访问),当使用完后,使用shmctl释放(shmctl还可以完成一些其他功能)。这种使用逻辑也适用于消息和信号量。示例程序代码如下:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(void)
{
int x, shmid;
int *shmptr;
if((shmid=shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666)) < 0)
printf("shmget error"), exit(1);
if((shmptr=(int *)shmat(shmid, 0, 0)) == (int *)-1)
printf("shmat error"), exit(1);
printf("Input a initial value for *shmptr: ");
scanf("%d", shmptr);
while((x=fork())==-1);
if(x==0)
{
printf("When child runs, *shmptr=%d\n", *shmptr);
printf("Input a value in child: ");
scanf("%d", shmptr);
printf("*shmptr=%d\n", *shmptr);
}
else
{
wait();
printf("After child runs, in parent, *shmptr=%d\n", *shmptr);
if ( shmctl(shmid, IPC_RMID, 0) < 0 )
printf("shmctl error"), exit(1);
}
return 0;
}
输出结果:
Input a initial value for *shmptr:1
When child runs,*shmptr=1
Input a value in child:2
*shmptr=2
After child runs,in parent,*shmptr=2
分析:
Shmptr是建立一个父子进程共享存储区中数据,开始时,父进程执行,
给*shmptr赋值为1。通过fork()函数,父进程创建一子进程,子进程的
Fork()返回值为0,父进程的fork()返回值为子进程号,父子进程共享存
储区中数据*shmptr=1。系统默认子进程先执行(父进程处于就绪队列),
子进程的x=fork()=0,故执行if分支下语句,提示用户输入*shmptr的
值后,出现I/O中断,子进程释放处理机,进入就绪状态。处于就绪状
态的父进程获得处理机,继续执行,x=fork()=子进程号,进入else分支
下,执行Wait()操作(让子进程先执行完)。子进程执行接受输入数据
2赋值共享存储区的数据给*shmptr,并输出*shmptr=2,子进程执行完毕,
父进程获得处理机继续执行,因子进程已经改变了共享存储区的shmptr,
输出当前共享存储区的数据shmptr=2.