消息队列
包括消息类型和消息两部分,消息类型从1开始
获取消息输入什么接收什么,输0代表接受所有消息
msgget()创建消息
msgsnd()添加、发送消息
msgrcv()获取消息
msgctl() 控制 移除
//发送消息
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<sys/msg.h>
struct mess
{
long type;
char buff[128];
};
int main()
{
int msgid = msgget((key_t)1234,IPC_CREAT|0600);
assert(msgid! = -1);
struct mess dt;
dt.type = 1;//定义消息类型
strcpy(dt.buff,"hello1");//添加消息
msgsnd(msgid,&dt,128,0);//往创建好的msgid消息队列中添加dt中的数据,大小为数据的大小,也可以strlen(dt.buff),0表示标志位为默认,消息队列满则会阻塞。
exit(0);
}
//接收消息
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<assert.h>
#include<sys/msg.h>
struct mess
{
long type;
char buff[128];
};
int main()
{
int msgid = msgget((key_t)1234,IPC_CREAT|0600);
assert(msgid! = -1);
struct mess dt;
msgrcv(msgid,&dt,32,1,0);//从消息队列中读取消息
printf("%s\n",dt.buff);//打印消息
exit(0);
}