基本知识介绍参考:https://mp.weixin.qq.com/s/oSXUJiLT_qJoW4xk-zAf6g
进程间通信简称IPC(Inter process communication),进程间通信就是在不同进程之间传播或交换信息,通常采用的方法有共享内存、信号量、管道和消息队列等。
消息队列本质是一个存储消息的链表,这些消息具有特定的格式及特定优先级。消息队列是随内核持续的,只有在内核重启或删除一个消息队列时,该消息队列才会真正地被删除。
1.获取键值。
key_t ftok ( char *pathname, char proj_id );
2. 创建或打开消息队列
int msgget(key_t key ,int msgflg );
3. 发送消息
int msgsnd(int msgid, const void *msg_ptr, size_t msg_sz, int msgflg);
msg_ptr是一个指向准备发送消息的指针,但是消息的数据结构却有一定的要求,消息结构要定义如下格式:
msg_ptr是一个指向准备发送消息的指针,但是消息的数据结构却有一定的要求,消息结构要定义如下格式:
msg_sz为要发送消息的大小,不含消息类型占用字节。
msgflg为0表示当消息队列满时,msgsnd将会阻塞,直到消息能写进消息队列。
msg_sz为要发送消息的大小,不含消息类型占用字节。
msgflg为0表示当消息队列满时,msgsnd将会阻塞,直到消息能写进消息队列。
4. 接收消息
int msgrcv(int msgid, void *msg_ptr, size_t msg_st, long int msgtype, int msgflg);
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
代码放这了,可以直接下载测试
git clone https://github.com/zlshao/MQ_demo.git
sudo chmod 777 run.sh
./run.sh
会产生两个可执行文件,开两个终端分别运行就可以了。
下面简单讲解一下代码
syntax = "proto2";
package messageQ;message Msgbuf{optional int64 id=1;optional string text=2;}
#include
#include
#include
#include
#include
#include
using namespace std;#include"msg.pb.h"struct Msgstruct{long type; //类型是固定的,必须要有的char data[256]; //这里存放序列化后的proto消息!!!
};int main(){messageQ::Msgbuf sendData;//设置需要发送的消息,包括ID和textsendData.set_id(111); sendData.set_text("This is a protobuf message");//序列化为string发送。其实也可以直接序列化为数组string str=sendData.SerializePartialAsString();Msgstruct writeMsg;writeMsg.type=888; //888为消息类型strcpy(writeMsg.data,str.c_str());int msgID=msgget(0x1234,IPC_CREAT|0777);if(msgID==-1){cout<<"Failure!"<
#include
#include
#include
#include
#include
#include#include"msg.pb.h"using namespace std;struct Msgstruct{long type;char data[256];
};int main(){Msgstruct readMsg;int msgID=msgget(0x1234,IPC_CREAT|0777);if(msgID==-1){cout<<"failure!"<