1 Star 0 Fork 0

WOODCOLA/linux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
msgqueue.hpp 2.66 KB
一键复制 编辑 原始数据 按行查看 历史
#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
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/woodcola/linux-c.git
git@gitee.com:woodcola/linux-c.git
woodcola
linux-c
linux
master

搜索帮助