1 Star 1 Fork 0

沈旭彬/C++代码

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
shared_memory.hpp 1.78 KB
一键复制 编辑 原始数据 按行查看 历史
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <cstring>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PATHNAME "/home/sxb/240416/shared_memory"
#define PROJ_ID 0x28364
#define DEFAULT_SIZE 4096
using namespace std;
key_t get_key(const char *pathname, int proj_id)
{
key_t key = ftok(pathname, proj_id);
// 成功返回key值,失败返回-1
if (key == -1)
{
cout << "获取key值失败,原因是:" << strerror(errno) << endl;
exit(1);
}
return key;
}
int get_or_create_shared_memory(key_t key, int size, int flag)
{
int shmid = shmget(key, size, flag);
// 成功返回共享内存标识符,失败返回-1
if (shmid == -1)
{
cout << "共享内存创建失败,原因是:" << strerror(errno) << endl;
exit(2);
}
return shmid;
}
int create_shared_memory(key_t key, int size)
{
return get_or_create_shared_memory(key, size, IPC_CREAT | IPC_EXCL | 0666);
}
int get_shared_memory(key_t key, int size)
{
return get_or_create_shared_memory(key, size, IPC_CREAT);
}
void *shm_attch(int shmid)
{
void *addr = shmat(shmid, nullptr, 0);
if ((long long int)addr == -1)
{
cerr << "挂接失败" << endl;
return nullptr;
}
else
cout << "挂接成功" << endl;
return addr;
}
void shm_detach(void *addr)
{
int ret = shmdt(addr);
if (ret == -1)
{
cerr << "去挂接失败" << endl;
}
else
cout << "去挂接成功" << endl;
}
void shm_del(int shmid)
{
int ret = shmctl(shmid, IPC_RMID, nullptr);
if (ret == -1)
cerr << "删除共享内存失败" << endl;
else
cout << "删除共享内存成功" << endl;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/shenxubin/d-code.git
git@gitee.com:shenxubin/d-code.git
shenxubin
d-code
C++代码
master

搜索帮助