1、消息队列:通过键盘来选择发送消息的标识
通过键盘指定标识对应的标识
发送消息
#include<stdio.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<string.h>
#include<sys/errno.h>
//创建msg结构体
struct msgbuf
{
long mtype;
char mtext[100];
};
int main()
{
//创建key值与msgid
int msg_id = msgget(ftok("./", 0), IPC_CREAT | 0666);
if(-1 == msg_id)
{
printf("获取id failed");
return -1;
}
//写入数据
//定义一个msgbuf结构体变量
struct msgbuf buf;
while(1)
{
//结构体清空
memset(buf.mtext, 0, 100);
//从键盘获取mtype
printf("请输入msgid\n");
scanf("%ld",&(buf.mtype));
//从键盘获取写入的内容
printf("请输入消息内容\n");
scanf("%s",buf.mtext);
//将数据写入消息队列
int snd_ret = msgsnd(msg_id,&buf,sizeof(buf),0);
if(-1 == snd_ret)
{
perror("send message failed");
}
//判断结束
if(strcmp(buf.mtext,"bey\n") == 0)
break;
}
return 0;
}
接收消息
#include<stdio.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<string.h>
#include<sys/errno.h>
//创建msg结构体
struct msgbuf
{
long mtype;
char mtext[100];
};
int main()
{
//创建key值与msgid
int msg_id = msgget(ftok("./", 0), IPC_CREAT | 0666);
if(-1 == msg_id)
{
printf("获取id failed");
return -1;
}
//写入数据
//定义一个msgbuf结构体变量
struct msgbuf buf;
while(1)
{
//结构体清空
memset(buf.mtext, 0, 100);
//从键盘获取mtype
printf("请输入msgid\n");
scanf("%ld",&(buf.mtype));
//将数据写入消息队列
int rv_ret = msgrcv(msg_id,&buf,sizeof(buf), buf.mtype,0);
if(-1 == rv_ret)
{
perror("recover message failed");
}
//打印消息
printf("%s",buf.mtext);
//判断结束
if(strcmp(buf.mtext,"bey\n") == 0)
break;
}
return 0;
}