发送方
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/msg.h>
#define MAXLENGTH 80
struct msg_st
{
long msgtype;
char text[MAXLENGTH];
};
int main()
{
int msgid,i;
char *snddata[4]={"Hello,world!","Prepare to rcv data!","Data is 1234!","end"};
struct msg_st msgsnddata;
msgid = msgget((key_t)1234,06666|IPC_CREAT);
if(msgid == -1)
exit(0);
while(i<4)
{
msgsnddata.msgtype = 1;
strcpy(msgsnddata.text,snddata[i]);
msgsnd(msgid,&msgsnddata,MAXLENGTH,0);
i++;
}
return 0;
}
#define MAXLENGTH 80约定消息队列中每条消息的最大长度,不可以超过系统规定的最大长度。
struct msg_st
{
long msgtype;
char text[MAXLENGTH];
};
约定每条消息的格式。long msgtype必须要有表示消息类型。text为内容,可以自己定义其它形式如int。
msgget((key_t)1234,06666|IPC_CREAT)中1234位消息队列的key,接收方需要使用。0666表示有读写权限,IPC_CREAT不存在则创建。
msgsnd(msgid,&msgsnddata,MAXLENGTH,0);中&msgsnddata为指针,MAXLENGTH数据长度,常用0
strcpy(msgsnddata.text,snddata[i]);将snddata[i]复制给前面,均为指针。
接收方
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/msg.h>
#define MSGLENGTH 80
struct msg_st
{
long msgtype;
char text[MSGLENGTH];
};
int main()//receive msg
{
int msgid,msgtype;
struct msg_st rcvdata;
msgid = msgget((key_t)1234,0666|IPC_CREAT);
if(msgid == -1)
{
printf("error msgget!\n");
exit(0);
}
msgtype = 0;//rcv first msg from queue
while(1)
{
msgrcv(msgid,&rcvdata,MSGLENGTH,msgtype,0);
if(strcmp(rcvdata.text,"end") == 0)
break;
else
printf("%s\n",rcvdata.text);
}
if(msgctl(msgid,IPC_RMID,0) == -1)//close msg queue
{
printf("error msgctl!\n");
exit(0);
}
return 0;
}
需要循环读取消息队列,msgrcv(msgid,&rcvdata,MSGLENGTH,msgtype,0);
msgtype为0表示每次读取第一条。数据读完就没了。
msgctl(msgid,IPC_RMID,0)读完数据后关闭消息队列。