操作系统进程间消息队列通信实验
进程间消息队列通信实验所用函数说明
实现代码如下:
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include<stdlib.h>
#include<unistd.h>
#define MSGKEY 75
struct msgform
{
long mtype;
char mtrex[1024];
}msg;
int msgqid,i;
void CLIENT()
{
int i;
msgqid=msgget(MSGKEY,0777|IPC_CREAT);
for(i=10;i>=1;i--)
{
msg.mtype=i;
int j=0;
while((msg.mtrex[j++]=getchar())!='\n');
printf("{client}sent\n");
msgsnd(msgqid,&msg,1024,0);
}
exit(0);
}
void SERVER()
{
msgqid=msgget(MSGKEY,0777|IPC_CREAT);
do
{
msgrcv(msgqid,&msg,1024,0,0);
printf("(server)received,%s",msg.mtrex);
}while(msg.mtype!=1);
msgctl(msgqid,IPC_RMID,0);
exit(0);
}
void main()
{
while((i=fork())==-1);
if(!i) CLIENT();
else
{
while((i=fork())==-1);
if(!i) SERVER();
else
{
wait(0);
wait(0);
}
}
}
实验结果: