2.要求用消息队列实现AB进程对话:1) A进程发送句话,B进程接收后打印;2) B进程接着再发送句话, A进程接收打印;3)重复上述步骤,当A进程或者B进程接收到quit后退出AB进程。

#include <stdio.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <string.h>
#include <stdlib.h>
struct msgbuf
{
	long mtype;
	char mtext[128];
};
int main(int argc, const char *argv[])
{
    //key值 	
	key_t key;
	key=ftok("./",4);
    if(key<0)
	{
		perror("ftok");
	}
	//创建消息队列
	int qid;
	qid=msgget(key,IPC_CREAT|0664);
	{
		if(qid<0)
		{
			perror("msgget");
		}
	}
	struct msgbuf msgp;
	while(1)
	{
	msgp.mtype=1;
	printf("请输入向B进程发布的消息\n");
	fgets(msgp.mtext,sizeof(msgp.mtext),stdin);
    msgp.mtext[strlen(msgp.mtext)-1]='\0';
	//向消息队列写入	
	int snd;
    snd=msgsnd(qid,&msgp,sizeof(msgp.mtext),IPC_NOWAIT);
	   if(snd<0)
	   {
		   perror("snd");
	   }
	 if(strcmp(msgp.mtext,"quit")==0)
	 {
		 break;
	 }
	//从消息队列读取
	int rcv;
    rcv=msgrcv(qid,&msgp,sizeof(msgp.mtext),2,0);
	   if(rcv<0)
	   {
	  	   perror("rcv");
	       break;
	   }
	   printf("读取到的数据%s\n",msgp.mtext);
	 if(strcmp(msgp.mtext,"quit")==0)
	 {
		 break;
	 }
	}

	return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <string.h>
#include <stdlib.h>
struct msgbuf
{
	long mtype;
	char mtext[128];
};
int main(int argc, const char *argv[])
{
    //key值 	
	key_t key;
	key=ftok("./",4);
    if(key<0)
	{
		perror("ftok");
	}
	//创建消息队列
	int qid;
	qid=msgget(key,IPC_CREAT|0664);
	{
		if(qid<0)
		{
			perror("msgget");
		}
	}
	struct msgbuf msgp;
	while(1)
	{
		memset(&msgp,0,sizeof(msgp));
	//从消息队列读取	
	int rcv;
    rcv=msgrcv(qid,&msgp,sizeof(msgp.mtext),1,0);
	   if(rcv<0)
	   {
	  	   perror("rcv");
	       break;
	   }
	 if(strcmp(msgp.mtext,"quit")==0)
	 {
		 break;
	 }
	   printf("读取到的数据%s\n",msgp.mtext);	
	   //向消息队列写入
	msgp.mtype=2;
	printf("请输入向A进程发布的消息\n");
	fgets(msgp.mtext,sizeof(msgp.mtext),stdin);
    msgp.mtext[strlen(msgp.mtext)-1]='\0';
	  int snd;
    snd=msgsnd(qid,&msgp,sizeof(msgp.mtext),IPC_NOWAIT);
	   if(snd<0)
	   {
		   perror("snd");
	   }
	 if(strcmp(msgp.mtext,"quit")==0)
	 {
		 break;
	 }
    }
	return 0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值