新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c++如何创建共享内存,c$默认共享

发布时间:2023-08-21 07:56:30

c++如何创建共享内存

在C++中,可使用操作系统的系统调用还是第三方库来创建共享内存。
1. 使用操作系统的系统调用:
在Unix/Linux操作系统中,可使用shmget函数来创建共享内存。具体步骤以下:
```cpp
#include
#include
#include
int main() {
key_t key = ftok("shmfile",65); // 生成一个唯一的key
int shmid = shmget(key,1024,0666|IPC_CREAT); // 创建共享内存,大小为1024字节
if (shmid == ⑴) {
std::cout << "Failed to create shared memory!" << std::endl;
return 1;
}
std::cout << "Shared memory created with ID: " << shmid << std::endl;
return 0;
}
```
在Windows操作系统中,可使用CreateFileMapping函数来创建共享内存。具体步骤以下:
```cpp
#include
#include
int main() {
HANDLE hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024, "SharedMemory"); // 创建共享内存,大小为1024字节
if (hMapFile == NULL) {
std::cout << "Failed to create shared memory!" << std::endl;
return 1;
}
std::cout << "Shared memory created with handle: " << hMapFile << std::endl;
return 0;
}
```
2. 使用第三方库:
使用第三方库可以简化共享内存的创建和管理进程。例如,可使用Boost.Interprocess库来创建共享内存。具体步骤以下:
```cpp
#include
#include
int main() {
boost::interprocess::shared_memory_object shm(boost::interprocess::create_only, "SharedMemory", boost::interprocess::read_write); // 创建共享内存
shm.truncate(1024); // 设置共享内存大小为1024字节
std::cout << "Shared memory created with handle: " << shm.get_handle() << std::endl;
return 0;
}
```
注意:使用Boost.Interprocess库需要先安装库文件并链接到项目中。
不管使用哪一种方法,创建共享内存后,就能够在其他进程中通过相同的key还是名称打开该共享内存,并进行读写操作。