在Linux中,C++可以使用POSIX共享内存API或System V共享内存API来创建和使用共享内存。以下是使用POSIX共享内存API的一个基本示例:
#include <iostream>
#include <fcntl.h> // For O_* constants
#include <sys/mman.h> // For mmap()
#include <unistd.h> // For close()
#include <cstring> // For memset()
const char* shm_name = "/my_shm";
int shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open");
exit(EXIT_FAILURE);
}
size_t shm_size = 1024; // 1KB
if (ftruncate(shm_fd, shm_size) == -1) {
perror("ftruncate");
exit(EXIT_FAILURE);
}
void* ptr = mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
// 写入数据到共享内存
std::string message = "Hello, shared memory!";
memcpy(ptr, message.c_str(), message.size() + 1); // +1 for the null terminator
// 读取共享内存中的数据
std::cout << "Message from shared memory: " << static_cast<char*>(ptr) << std::endl;
if (munmap(ptr, shm_size) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
if (close(shm_fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
// 删除共享内存对象(可选)
if (shm_unlink(shm_name) == -1) {
perror("shm_unlink");
exit(EXIT_FAILURE);
}
这是一个简单的例子,展示了如何在C++中使用POSIX共享内存API。在实际应用中,你可能需要考虑同步机制(如信号量)来避免竞态条件,以及错误处理和资源管理。
请注意,POSIX共享内存API是在Linux系统上使用的,而System V共享内存API是另一种在不同UNIX-like系统上可用的标准。如果你需要在不同的系统上编写可移植的代码,你可能需要根据目标平台选择合适的API或者使用跨平台的库,如Boost.Interprocess。