C++ 单例模式怎么放置在共享内存中并配置信号量
运行环境: Fedora Server 41
话不多说,直接上代码:有空再写说明
main.cpp:
#include <iostream>
#include <fcntl.h> // For O_* constants
#include <sys/mman.h> // For shm_open and mmap
#include <sys/stat.h> // For mode constants
#include <unistd.h> // For ftruncate
#include <semaphore.h> // For sem_open and sem_wait
#include <cstring> // For memcpy
class SharedMemorySingleton {
private:
static const char* SHM_NAME;
static const char* SEM_NAME;
static const size_t SHM_SIZE;
int shm_fd;
void* shm_ptr;
sem_t* semaphore;
// Private constructor to enforce singleton pattern
SharedMemorySingleton() {
// Create or open shared memory
shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0666);
if (shm_fd == -1) {
perror("shm_open");
exit(EXIT_FAILURE);
}
// Resize shared memory
if (ftruncate(shm_fd, SHM_SIZE) == -1) {
perror("ftruncate");
exit(EXIT_FAILURE);
}
// Map shared memory to process's address space
shm_ptr = mmap(0, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (shm_ptr == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
// Create or open semaphore
semaphore = sem_open(SEM_NAME, O_CREAT, 0666, 1);
if (semaphore == SEM_FAILED) {
perror("sem_open");
exit(EXIT_FAILURE);
}
}
// Delete copy constructor and assignment operator
SharedMemorySingleton(const SharedMemorySingleton&) = delete;
SharedMemorySingleton& operator=(const SharedMemorySingleton&) = delete;
public:
~SharedMemorySingleton() {
// Cleanup resources
munmap(shm_ptr, SHM_SIZE);
close(shm_fd);
sem_close(semaphore);
}
static SharedMemorySingleton& getInstance() {
static SharedMemorySingleton instance;
return instance;
}
void writeData(const std::string& data) {
// Lock semaphore
sem_wait(semaphore);
// Write data to shared memory
if (data.size() > SHM_SIZE) {
std::cerr << "Data size exceeds shared memory size" << std::endl;
} else {
memcpy(shm_ptr, data.c_str(), data.size() + 1); // +1 for null terminator
}
// Unlock semaphore
sem_post(semaphore);
}
std::string readData() {
// Lock semaphore
sem_wait(semaphore);
// Read data from shared memory
char buffer[SHM_SIZE];
memcpy(buffer, shm_ptr, SHM_SIZE);
// Unlock semaphore
sem_post(semaphore);
return std::string(buffer);
}
};
// Static member definitions
const char* SharedMemorySingleton::SHM_NAME = "/my_shared_memory";
const char* SharedMemorySingleton::SEM_NAME = "/my_semaphore";
const size_t SharedMemorySingleton::SHM_SIZE = 1024;
int main() {
SharedMemorySingleton& singleton = SharedMemorySingleton::getInstance();
singleton.writeData("Hello from shared memory!");
std::cout << "Data read from shared memory: " << singleton.readData() << std::endl;
return 0;
}
本文来自博客园,作者:mariocanfly,转载请注明原文链接:https://www.cnblogs.com/mariocanfly/p/18803119

浙公网安备 33010602011771号