#pragma once #include #include #include #include #include #include #include #include #include // ============== 轻量 INI 配置文件读写(Linux)============== // 配置文件路径: ~/.config/ghost/*.conf // 格式: key=value(按行存储,不分 section) class LinuxConfig { public: // 使用指定配置文件名(如 "screen" -> ~/.config/ghost/screen.conf) explicit LinuxConfig(const std::string& name = "config") { const char* xdg = getenv("XDG_CONFIG_HOME"); if (xdg && xdg[0]) { m_dir = std::string(xdg) + "/ghost"; } else { const char* home = getenv("HOME"); if (!home) home = "/tmp"; m_dir = std::string(home) + "/.config/ghost"; } m_path = m_dir + "/" + name + ".conf"; Load(); } std::string GetStr(const std::string& key, const std::string& def = "") const { auto it = m_data.find(key); return it != m_data.end() ? it->second : def; } void SetStr(const std::string& key, const std::string& value) { SetValue(key, value); } int GetInt(const std::string& key, int def = 0) const { auto it = m_data.find(key); if (it != m_data.end()) { try { return std::stoi(it->second); } catch (...) {} } return def; } void SetInt(const std::string& key, int value) { SetValue(key, std::to_string(value)); } // 重新加载配置 void Reload() { Load(); } private: std::string m_dir, m_path; std::map m_data; void Load() { m_data.clear(); std::ifstream f(m_path); std::string line; while (std::getline(f, line)) { size_t eq = line.find('='); if (eq != std::string::npos) { m_data[line.substr(0, eq)] = line.substr(eq + 1); } } } // 写一个键。主实例和分享子进程写的是同一个文件,各持一份整文件快照、整文件覆盖 // 写,所以必须「拿跨进程锁 -> 重读 -> 改一个键 -> 原子替换」:不重读会把对方刚 // 写的键(比如 transfer)整个抹掉,不原子替换则可能被读到写了一半的文件。 void SetValue(const std::string& key, const std::string& value) { MkdirRecursive(m_dir); // O_CLOEXEC:锁 fd 不能漏给 fork+exec 出来的分享子进程,否则它会把锁一直 // 持有到自己退出。close() 即释放 flock。 int lockFd = open((m_path + ".lock").c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0644); if (lockFd >= 0) flock(lockFd, LOCK_EX); Load(); m_data[key] = value; SaveAtomic(); if (lockFd >= 0) close(lockFd); } // 先写同目录临时文件再 rename:同一文件系统内 rename 是原子的,读者要么看到 // 旧文件、要么看到新文件,不会读到截断到一半的内容。 void SaveAtomic() { const std::string tmp = m_path + ".tmp." + std::to_string((long)getpid()); { std::ofstream f(tmp, std::ios::trunc); if (!f.is_open()) return; // 打开失败:保留旧文件 for (auto& kv : m_data) f << kv.first << "=" << kv.second << "\n"; f.flush(); if (!f) { remove(tmp.c_str()); return; } } if (rename(tmp.c_str(), m_path.c_str()) != 0) remove(tmp.c_str()); } // 递归创建目录 static void MkdirRecursive(const std::string& path) { size_t pos = 0; while ((pos = path.find('/', pos + 1)) != std::string::npos) { mkdir(path.substr(0, pos).c_str(), 0755); } mkdir(path.c_str(), 0755); } };