C++怎么实现共享内存

655Z技术栈 C/C++编程 2025年06月21日 9

C++中可以使用System V共享内存和POSIX共享内存来实现共享内存。

  1. 使用System V共享内存:

首先,需要包含<sys/ipc.h>和<sys/shm.h>头文件。

  • 调用shmget()函数创建或获取共享内存标识符。

  • 调用shmat()函数将共享内存连接到当前进程的地址空间。

  • 使用共享内存进行读写操作。

  • 调用shmdt()函数将共享内存与当前进程分离。

  • 调用shmctl()函数删除共享内存。

  1. 使用POSIX共享内存:

首先,需要包含<fcntl.h>和<sys/mman.h>头文件。

  • 调用shm_open()函数创建或获取共享内存对象。

  • 使用ftruncate()函数设置共享内存对象的大小。

  • 调用mmap()函数将共享内存对象映射到进程的地址空间。

  • 使用共享内存进行读写操作。

  • 调用munmap()函数解除共享内存对象的映射。

  • 调用shm_unlink()函数删除共享内存对象。

以下是使用System V共享内存的示例代码:

#include <iostream> #include <sys/ipc.h> #include <sys/shm.h> int main() { key_t key = ftok("shared_memory", 1234); // 生成共享内存的key int shm_id = shmget(key, 1024, IPC_CREAT | 0666); // 创建共享内存段 char* shm_addr = (char*)shmat(shm_id, nullptr, 0); // 连接共享内存 // 写入数据到共享内存 strcpy(shm_addr, "Hello, shared memory!"); // 从共享内存读取数据 std::cout << "Message from shared memory: " << shm_addr << std::endl; shmdt(shm_addr); // 分离共享内存 shmctl(shm_id, IPC_RMID, nullptr); // 删除共享内存段 return 0; }

注意:使用共享内存时需要确保不同进程之间对共享内存的读写操作的同步和互斥,以避免数据不一致的问题。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”