//
// Created by HP on 2025/9/30.
//
#ifndef SIFANG103_OPTION_H
#define SIFANG103_OPTION_H
#include <iostream>
#include <sys/shm.h>
#include <cstring>
#include <fcntl.h>
class Option {
public:
explicit Option() {
/* 获取对应的环境变量 */
auto tmp = getenv("HOTSTANDBY");
if (tmp) {
env = tmp;
}
/* 获取对应的共享内存 */
int shm_id = shmget((key_t) 1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shm_id == -1) {
throw std::runtime_error(std::string("共享内存获取/创建失败: ") + strerror(errno));
}
// 附加到共享内存段
auto shm_addr = shmat(shm_id, nullptr, 0);
if (shm_addr == (void *) -1) {
throw std::runtime_error(std::string("附加到共享内存段失败: ") + strerror(errno));
}
// 拷贝共享内存值
std::memcpy(&shared, shm_addr, sizeof(shared_use_st));
// 分离共享内存
auto res = shmdt(shm_addr);
if (res == -1) {
throw std::runtime_error(std::string("共享内存分离失败: ") + strerror(errno));
}
}
~Option() = default;
bool isMasterSlaveMode() {
return env == "1";
}
bool isMaster() {
bool ret = strncmp(shared.text, "1", 1) == 0;
return ret;
}
private:
std::string env; /* 环境变量 用于标识是否处于主辅机(运行)状态 */
struct shared_use_st {
int written;
char text[256];
};
struct shared_use_st shared{}; /* 指向读取出的共享内存的指针 */
};
#endif //SIFANG103_OPTION_H