《实验项目四》由会员分享,可在线阅读,更多相关《实验项目四(5页珍藏版)》请在金锄头文库上搜索。
1、实验项目四 进程通信一、 实验目的1. 了解什么是消息,熟悉消息传送原理。2. 了解和熟悉共享存储机制。3. 掌握消息的发送与接收的实现方法。二、 实验内容1. 根据消息传送机理,使用系统调用msgget( ), msgsnd( ), msgrev( ), 及msgctl( )编制一长度为k的消息发送和接收的程序,要求在程序中完成10次消息的发送和接收,每次发送消息结束和接收消息结束都需给出相应的屏幕提示,且每次发送的的内容不少于一个字符,并能在接收端输出。2. 根据共享存储区原理,使用系统调用shmget( ), shmat( ), shmdt( ), 及shctl( )编制程序,要求创建一
2、个长度为k的共享存储区,并完成10次数据的发送和接收,每次发送数据结束和接收数据结束都需给出相应的屏幕提示,且每次发送的的数据应能在接收端输出。三、 源程序及运行结果1. 源程序: #include #include #include #include #include #define MSGKEY 75struct msgformlong mtype;char mtext1024;msg;int msgqid;void client()int i=0;for(;i10;i+)msgqid=msgget(MSGKEY,0777);msg.mtype=1;msg.mtext1=i+0;print
3、f( send %dn,i+0);msgsnd(msgqid,&msg,1024,0);sleep(1);exit(0);void main()client();#include #include #include #include #include #define MSGKEY 75 struct msgformlong mtype;char mtext1024;msg;int msgqid;void server()int i=0;while(1)int count=0;msgqid=msgget(MSGKEY,0777|IPC_CREAT);msgrcv(msgqid,&msg,1024
4、,0,0);printf( get message);printf(%dn,msg.mtextmsg.mtype);msgctl(msgqid,IPC_RMID,0);count+;if(count=9)exit(0);int main()server();return 0;运行结果:(截图)2源程序:#include #include #include #include #include #define SHMKEY 75int main()int shmid;int *addr;int i=0;shmid=shmget(SHMKEY,1024,0777);addr=shmat(shmid,
5、0,0);while( i10)if(*addr=0)*(addr+1)=a+i; printf(client send message_%cn,*(addr+1);i+;*addr=1;elsesleep(1);return 0;#include #include #include #include #include #define SHMKEY 75int main()int shmid;int i=0;int *addr;shmid=shmget(SHMKEY,1024,0777|IPC_CREAT);addr=shmat(shmid,0,0);*addr=0;while(i10)if(*addr=0)sleep(1);elseprintf(server get message_%cn,*(addr+1);*addr=0;i+;shmctl(shmid,IPC_RMID,0);exit(0);运行结果:(截图)四、 实验分析与总结对实验运行结果进行分析:试比较实验中两种方法实现进程通信的不同之处。