进程间通信—消息队列(二)

实例:模拟经纬度的收发工作。(采用消息队列的方式处理)
项目中涉及2个不相关进程A和进程B

假设你是项目的进程A编写者,你负责把进程A的经纬度发送到

第三方导航软件中导航定位(进程B)进程A每2秒发送一次经纬度,

进程B每3秒接受一次经纬度并打印显示。


上海默认是北纬东经

数据体(body)协议:
      int header;//1000
      //122.33字符串
      char longitude[16];
      //29.444字符串

      char latitude[16]

这个例子需要用到两个程序,send.c和receive.c

send.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
//#define MAX_SEND_SIZE 80
struct mymsgbuf
{
	int mtype;
	char longitude[16];
	char latitude[16];
};
void send_message(int qid,struct mymsgbuf *qbuf,int type,char *mlongitude,char *mlatitude)
{
	printf("Sending a message...\n");
	qbuf->mtype=type;
	strcpy(qbuf->longitude,mlongitude);
	strcpy(qbuf->latitude,mlatitude);
	if((msgsnd(qid,(struct msgbuf *)qbuf,sizeof(struct mymsgbuf)-4,0))==-1)
	{
		perror("msgsnd");
		exit(0);
	}
}
int main()
{
	key_t key;
	int msgqueue_id;
	struct mymsgbuf qbuf;
	key=ftok(".",'m');
	if((msgqueue_id = msgget(key,IPC_CREAT|0777))==-1)
	{
		perror("msgget");
		exit(1);
	}
	while(1)
	{
		send_message(msgqueue_id,(struct mymsgbuf *)&qbuf,1000,"122.33","29.444");
	}
	return 0;
}
		
		
recv.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mymsgbuf
{
	int mtype;
	char longitude[16];
	char latitude[16];
};
void read_message(int qid,struct mymsgbuf *qbuf,int type)
{
	printf("Reading a message...\n");
	qbuf->mtype=type;
	msgrcv(qid,(struct msgbuf *)qbuf,sizeof(struct mymsgbuf)-4,type,0);
	printf("Type:%ld longitude:%s, latitude:%s\n",qbuf->mtype,qbuf->longitude,qbuf->latitude);
}

int main()
{
	
	key_t key;
	int msgqueue_id;
	struct mymsgbuf qbuf;
	key=ftok(".",'m');
	if((msgqueue_id = msgget(key,IPC_CREAT|0777))==-1)
	{
		perror("msgget");
		exit(1);
	}
	while(1)
	{
		read_message(msgqueue_id,&qbuf,1000);
		sleep(3);
	}
	return 0;
}

程序运行结果:



这样就实现了简单的进程间消息传递;

如果发送方没有发送消息,那么接收方就一直等待接受。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值