//msgrcv 为阻塞函数
/*A process create msg and send msg*/
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
#include<sys/types.h>
struct msgbuf
{
long type;
char data[100];
}
main()
{
//1.create messge queue
key_t key=ftok(".",254);
int msgid=msgget(key,IPC_CREAT|IPC_EXCL|0666);
//2.contruct data
int i;
for(i=0;i<10;i++)
{
struct msgbuf msg={};
msg.type=1;
sprintf(msg.data,"%s:%d","message",i);
//3.send message
msgsnd(msgid,&msg,sizeof(msg.data),0);
}
for(i=0;i<10;i++)
{
struct msgbuf msg={};
msg.type=2;
sprintf(msg.data,"%s:%d","messagetype2",i);
msgsnd(msgid,&msg,sizeof(msg.data),0);
}
//4.delete queue
// msgctl(msgid,IPC_RMID,0);
}
===================================================
/*B process open msg queue and read msg*/
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
struct msgbuf
{
long type;
char data[100];
}
main()
{
//1.open messge queue
key_t key=ftok(".",254);
int msgid=msgget(key,0);
//2.receive message
while(1)
{
struct msgbuf buf={};
msgrcv(msgid,&buf,sizeof(buf.data),2,0);
printf(":%s\n",buf.data);
sleep(1);
}
//3.delete queue
msgctl(msgid,IPC_RMID,0);
}