介绍
消息队列是Linux进程间通信的一种方式,可以把它理解为超市的储物柜,一个消息队列就是一个储物柜,而对应的类型就是储物柜格子编码。编码对应,就能存取对应的物品(数据);
函数
//创建以及获取队列
int msgget(key_t key, int msgflg)
//发送数据到队列
int msgsnd(int msqid, struct msgbuf *msgp, int msgsz, int msgflg)
//从队列接收数据
int msgrcv(int msqid, struct msgbuf *msgp, int msgsz, long mtype, int msgflg)
//用于删除队列
int msgctl(int msqid,int cmd,struct msqid_ds *buf)
举例
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#define MSGKEY 1234
struct msgbuf{
long mtype;
char mtext[100];
};
int main(){
pid_t pid;
pid = fork();
if(pid ==-1){
perror("fork");
exit(1);
}
else if(pid >0){
int msgid;
int ret;
struct msgbuf mbuf;
msgid = msgget(MSGKEY,IPC_CREAT); //创建队列,不加IPC_EXCL的话,意思就是队列已存在就直接用,MSGKEY为队列关键字,相当于队列的ID。
if(msgid == -1){
perror("msgget");
exit(1);
}
mbuf.mtype = 1; //设置数据类型,理解为超市的储物柜格子“密码”
strcpy(mbuf.mtext,"Hello, This is a msg text");
ret = msgsnd(msgid,&mbuf,sizeof(mbuf.mtext),0); //发送数据到队列中,0标识阻塞方式
if(ret == -1){
perror("msgsnd");
exit(1);
}
printf("msg has sent!\n");
sleep(1);
}
else{
int msgid;
int ret;
struct msgbuf mbuf;
sleep(1);
msgid = msgget(MSGKEY,0); //获取消息队列
if(msgid == -1){
perror("msgget");
exit(1);
}
mbuf.mtype = 1; //设置数据类型,即超市储物柜格子的“密码”
ret = msgrcv(msgid,&mbuf,sizeof(mbuf.mtext),1,0); //取出数据
if(ret == -1){
perror("msgrcv");
exit(1);
}
printf("Got the msg type: %s\n",mbuf.mtext);
msgctl(msgid,IPC_RMID,NULL); //用完删除队列
}
return 0;
}