实验项目四
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实验项目四进程通信
一、实验目的
1.了解什么是消息,熟悉消息传送原理。
2.了解和熟悉共享存储机制。
3.掌握消息的发送与接收的实现方法。
二、实验内容
1.根据消息传送机理,使用系统调用msgget( ), msgsnd( ),
msgrev( ), 及msgctl( )编制一长度为1k的消息发送和接收的
程序,要求在程序中完成10次消息的发送和接收,每次发送
消息结束和接收消息结束都需给出相应的屏幕提示,且每次
发送的的内容不少于一个字符,并能在接收端输出。
2.根据共享存储区原理,使用系统调用shmget( ), shmat( ),
shmdt( ), 及shctl( )编制程序,要求创建一个长度为1k的共
享存储区,并完成10次数据的发送和接收,每次发送数据结
束和接收数据结束都需给出相应的屏幕提示,且每次发送的
的数据应能在接收端输出。
三、源程序及运行结果
1.源程序:
#include
#include
#include
#include
#include
#define MSGKEY 75
struct msgform
{
long mtype;
char mtext[1024];
}msg;
int msgqid;
void client()
{
int i=0;
for(;i<10;i++)
{
msgqid=msgget(MSGKEY,0777);
msg.mtype=1;
msg.mtext[1]=i+0;
printf(" send %d\n",i+0);
msgsnd(msgqid,&msg,1024,0);
sleep(1);
}
exit(0);
}
void main()
{
client();
}
#include
#include
#include
#include
#include
#define MSGKEY 75
struct msgform
{
long mtype;
char mtext[1024];
}msg;
int msgqid;
void server()
{
int i=0;
while(1)
{ int count=0;
msgqid=msgget(MSGKEY,0777|IPC_CREAT);
msgrcv(msgqid,&msg,1024,0,0);
printf(" get message");
printf("%d\n",msg.mtext[msg.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 75
int main()
{
int shmid;
int *addr;
int i=0;
shmid=shmget(SHMKEY,1024,0777);
addr=shmat(shmid,0,0);
while( i<10)
{
if(*addr==0)
{
*(addr+1)='a'+i;
printf("client send message__%c\n",*(addr+1));
i++;
*addr=1;
}
else
sleep(1);
}
return 0;
}
#include
#include
#include
#include
#include
#define SHMKEY 75
int main()
{
int shmid;
int i=0;
int *addr;
shmid=shmget(SHMKEY,1024,0777|IPC_CREAT);
addr=shmat(shmid,0,0);
*addr=0;
while(i<10)
{
if(*addr==0)
sleep(1);
else
{
printf("server get message__%c\n",*(addr+1));
*addr=0;
i++;