/*让结构体指针指向这块共享内存*/
shared_stuff=(struct shared_use_st *)shared_memory;
/*循环的向共享内存中写数据,直到写入的为“end”为止*/
while(running)
{
while(shared_stuff->written_by_you==1)
{
sleep(1);//等到读进程读完之后再写
printf("waiting for client...\n");
}
printf("Ener some text:");
fgets(buffer,BUFSIZ,stdin);
strncpy(shared_stuff->some_text,buffer,TEXT_SZ);
shared_stuff->written_by_you=1;
if(strncmp(buffer,"end",3)==0)
{
running=0; //结束循环
}
}
/*删除共享内存*/
if(shmdt(shared_memory)==-1)
{
fprintf(stderr,"shmdt failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
3 . 在一个终端中运行shm1,在另一个终端中运行shm2.当shm1运行起来之后,由于共享内存中没有数据可读,会处于等待状态
[root@localhost 2-4-4]# ./shm1
Memory attached at B7F9A000
/***阻塞***/
再向shm2运行的终端输入字符串
[root@localhost 2-4-4]# ./shm2
Memory attached at B7FD8000
Enter some text:Impossible is nothing
waiting for client。。。
waiting for client。。。
Enter some text:Anything is possible
waiting for client。。。
Ener some text:end
[root@localhost 2-4-4]#
shm1能够逐个从共享内存中巴他们读出来,知道双方晕倒字符串"end"后,两个程序都退出。
[root@localhost 2-4-4]# ./shm1
Memory attached at B7F9A000
You write:Impossible is nothing
You write:Anything is possible
You write:end
[root@localhost 2-4-4]#
以上运行过程中,红色表示在终端1中运行的结果,蓝色表示在终端2里面运行的结果。