实例:模拟经纬度的收发工作。(采用消息队列的方式处理)
项目中涉及2个不相关进程A和进程B
int header;//1000
//122.33字符串
char longitude[16];
//29.444字符串
程序运行结果:
项目中涉及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;
}
程序运行结果:
这样就实现了简单的进程间消息传递;
如果发送方没有发送消息,那么接收方就一直等待接受。