代码拉取完成,页面将自动刷新
#ifndef MSGQUEUE_HPP
#define MSGQUEUE_HPP
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
#include <cstring>
#define CREAT_MSG (IPC_CREAT | IPC_EXCL | 0666)
#define GET_MSG (IPC_CREAT)
#define PATHNAME "/tmp"
#define KEYNUM 0x1314520
#define MAX_SIZE 1024
#define Client 1
#define Server 2
struct msgbuf1
{
long mtype; /* message type, must be > 0 */
char mtext[MAX_SIZE]; /* message data */
};
enum class status
{
key_not_create = 1,
msg_not_create
};
class Msgqueue
{
key_t Getkey()
{
key_t tmp = ftok(PATHNAME, KEYNUM);
if (tmp < 0)
{
std::cerr << "key not create" << std::endl;
exit(static_cast<int>(status::key_not_create));
}
return tmp;
}
public:
Msgqueue() : _key(-1), _msg_id(-1)
{
}
void CreateMsgqueue(int flag)
{
// 1.获取key
_key = Getkey();
// 2.创建消息队列
_msg_id = msgget(_key, flag);
if (_msg_id < 0)
{
std::cerr << "_msg not creat" << std::endl;
exit(static_cast<int>(status::msg_not_create));
}
}
bool Msgqueue_Send(const std::string& text,long flag)
{
struct msgbuf1 buffer;
memset(&buffer,0,sizeof buffer);
buffer.mtype = flag;
memcpy(buffer.mtext,text.c_str(),text.size());
int n = msgsnd(_msg_id,&buffer,MAX_SIZE,0);
if(n<0)
return false;
return true;
}
bool Msgqueue_Recv(std::string* text,long flag)
{
struct msgbuf1 buffer;
memset(&buffer,0,sizeof buffer);
int n =msgrcv(_msg_id,&buffer,MAX_SIZE,flag,0);
if(n<0)
return false;
buffer.mtext[n] = 0;
*text = buffer.mtext;
return true;
}
void Delete_Msgqueue()
{
// 该函数只给client端使用,我们让client 去读数据,让它管理资源
int n = msgctl(_msg_id, IPC_RMID, nullptr);
(void)n;
std::cout << "delete finish" << std::endl;
}
virtual ~Msgqueue()
{
}
private:
key_t _key;
int _msg_id;
};
class Client_Msgqueue : public Msgqueue
{
public:
Client_Msgqueue() {
this->CreateMsgqueue(CREAT_MSG);
std::cout<<"creat finish client"<<std::endl;
}
~Client_Msgqueue() {
this->Delete_Msgqueue();
}
private:
};
class Server_Msgqueue : public Msgqueue
{
public:
Server_Msgqueue() {
this->CreateMsgqueue(GET_MSG);
std::cout<<" get finsh server"<<std::endl;
}
~Server_Msgqueue() {}
private:
};
#endif // MSGQUEUE.HPP
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。