1 编写 A 程序 往共享内存 写入 Student_T 结构体,
B 程序往共享内存读 Student_T 结构体
#include "public.h"
int main()
{
SNode student;
char buffer[20];
pid_t pid=0;
int i=1;
int ret=0;
//开辟一个可以存储10个学生信息的共享内存空间
mem_no=shmget(MEM_KEY,10*MEM_SIZE,MEM_FLAG);
if (mem_no==-1)
{
printf("fail to shmget\n");
exit(0);
}
//共享内存的周地址映射到本进程
pstudent=(StuNodes)shmat(mem_no,NULL,0);
//保留开始的位置方便后续读取
pstudent_first=pstudent;
pstudent_first2=pstudent;
//学如学生到共享内存中
for (i=0;i<10;i++)
{
student.no=i;
sprintf(buffer,"student %d",i);
strcpy(student.username,buffer);
memcpy(pstudent,&student,MEM_SIZE);
//移动共享内存到下一个位置进行写入
pstudent++;
printf("write %d student \n",i);
sleep(1);
}
pid=fork();
if (pid==-1)
{
printf("进程分裂失败\n");
return 0;
}
if (pid==0)
{
//共享内存中读取数据
printf("开始从共享内存中读取数据。。。\n");
for (i=0;i<10;i++)
{
printf("student.no = %d student.username %s \n",pstudent_first->no,pstudent_first2->username);
pstudent_first++;
sleep(1);
}
//卸载共享内存
if (shmdt(pstudent_first2)==-1)
{
printf("fail to dattach share memory\n");
}
printf("press any key to remove share momory...\n");
getchar();
//删除共享内存
if (shmctl(mem_no,IPC_RMID,0)==-1)
{
printf("fail to IPC_RMID\n");
}
}
else if (pid>0)
{
sleep(13);
}
getchar();
return 0;
}