mymsg.h
#ifndef __MYMSG_H__
#define __MYMSG_H__
#define N 32
struct mydata{
int a;
int b;
};
struct msgbuf{
long mtype; /* message type, must be > 0 */
char mtext[sizeof(struct mydata)]; /* message data */
};
#endif
msg_snd.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <string.h>
#include "mymsg.h"
struct mydata data1 = {11,21},data2 = {31,41},data3 = {51,61};
struct msgbuf msgp[3] = {
[0] = {
.mtype = 1,
},
[1] = {
.mtype = 1,
},
[2] = {
.mtype = 2,
}
};
void mycp(char *dest,char *src,int n)
{
int i = 0;
for(;i < n;i++)
{
*dest = *src;
dest++;
src++;
}
return ;
}
int main(int argc, char const *argv[])
{
int i = 0;
int msgid = msgget((key_t)12,IPC_CREAT|IPC_EXCL|0644);
if(msgid < 0)
{
if(errno == EEXIST)
{
msgid = msgget((key_t)12,0644);
}
else
{
perror("msgid");
return -1;
}
}
#if 0
mycp(msgp[0].mtext,(char *)&data1,sizeof(struct mydata));
mycp(msgp[1].mtext,(char *)&data2,sizeof(struct mydata));
mycp(msgp[2].mtext,(char *)&data3,sizeof(struct mydata));
#else
memcpy(msgp[0].mtext,(char *)&data1,sizeof(struct mydata));
memcpy(msgp[1].mtext,(char *)&data2,sizeof(struct mydata));
memcpy(msgp[2].mtext,(char *)&data3,sizeof(struct mydata));
#endif
msgsnd(msgid,msgp,sizeof(struct mydata),0);
msgsnd(msgid,msgp+1,sizeof(struct mydata),0);
msgsnd(msgid,msgp+2,sizeof(struct mydata),0);
for(i = 0; i < 3 ; i++){
printf("msg %d:a = %d,b=%d\n",i,((struct mydata*)(msgp[i].mtext))->a,\
((struct mydata *)(msgp[i].mtext))->b);
}
return 0;
}
msg_rcv.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>
#include "mymsg.h"
#define MSG_EXCEPT 020000
int main(int argc, char const *argv[])
{
int i ;
struct msgbuf buf[3];
int msgid = msgget((key_t)12,IPC_CREAT|IPC_EXCL|0644);
if(msgid < 0)
{
if(errno == EEXIST)
{
msgid = msgget((key_t)12,0644);
}
else
{
perror("msgid");
return -1;
}
}
#if 1
msgrcv(msgid, buf, sizeof(struct mydata),1,0);
msgrcv(msgid, buf+1, sizeof(struct mydata),1,0);
msgrcv(msgid, buf+2, sizeof(struct mydata),2,0);
for(i = 0; i < 3 ; i++)
{
printf("masg %d:a = %d,b=%d\n",i,((struct mydata*)(buf[i].mtext))->a,\
((struct mydata *)(buf[i].mtext))->b);
}
#else
msgrcv(msgid, buf, sizeof(struct mydata),1,MSG_EXCEPT);
printf("msg 3:a = %d,b=%d\n",((struct mydata*)(buf[0].mtext))->a,\
((struct mydata *)(buf[0].mtext))->b);
#endif
return 0;
}
测试结果
ipcs -q
消息队列创建成功
发送消息队列
ipcs -q
可见目前有三条消息
接收消息队列
消息队列信息被读走