进程间共享内存(Inter-Process Communication, IPC)是一种允许多个进程访问同一块物理内存的机制。通过共享内存,进程可以高效地交换数据,避免了传统IPC方法(如管道、消息队列等)的开销。
在C++中,STL(Standard Template Library)提供了多种容器和算法。标准STL分配器通常不支持进程间共享内存,因为它们依赖于进程的地址空间。然而,可以通过自定义分配器来实现对共享内存的支持。
shm_open
和mmap
)来创建和管理共享内存段。以下是一个简单的示例,展示如何使用POSIX共享内存和自定义分配器来实现进程间共享内存。
#include <iostream>
#include <vector>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
template <typename T>
class SharedMemoryAllocator {
public:
using value_type = T;
SharedMemoryAllocator(const std::string& name, size_t size)
: shm_name(name), shm_size(size) {
shm_fd = shm_open(shm_name.c_str(), O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
throw std::runtime_error("Failed to open shared memory");
}
if (ftruncate(shm_fd, shm_size) == -1) {
close(shm_fd);
throw std::runtime_error("Failed to set shared memory size");
}
shm_ptr = mmap(nullptr, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (shm_ptr == MAP_FAILED) {
close(shm_fd);
throw std::runtime_error("Failed to map shared memory");
}
}
~SharedMemoryAllocator() {
munmap(shm_ptr, shm_size);
close(shm_fd);
shm_unlink(shm_name.c_str());
}
T* allocate(size_t n) {
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void deallocate(T* p, size_t n) {
::operator delete(p);
}
private:
std::string shm_name;
size_t shm_size;
int shm_fd;
void* shm_ptr;
};
int main() {
const std::string shm_name = "/my_shared_memory";
const size_t shm_size = 4096;
SharedMemoryAllocator<int> allocator(shm_name, shm_size);
std::vector<int, SharedMemoryAllocator<int>> shared_vector(allocator);
shared_vector.push_back(42);
std::cout << "Shared vector size: " << shared_vector.size() << std::endl;
return 0;
}
通过以上方法,可以实现进程间共享内存,并解决相关问题。
领取专属 10元无门槛券
手把手带您无忧上云