在 Linux + C++ 环境下,“配置怎么监控”通常有两种理解:
下面分别说常见做法,给你可直接用的方案。
适合监控:
.conf.yaml.json#include <sys/inotify.h>
#include <unistd.h>
#include <iostream>
int main() {
int fd = inotify_init();
int wd = inotify_add_watch(fd, "/etc/app/config.yaml",
IN_MODIFY | IN_CLOSE_WRITE);
char buf[1024];
while (true) {
int len = read(fd, buf, sizeof(buf));
if (len > 0) {
std::cout << "config changed, reload" << std::endl;
// 重新加载配置
}
}
}
✅ 优点:
#include <sys/stat.h>
#include <chrono>
#include <thread>
time_t last_mtime = 0;
void check_config(const char* path) {
struct stat st;
stat(path, &st);
if (st.st_mtime != last_mtime) {
last_mtime = st.st_mtime;
// reload
}
}
int main() {
while (true) {
check_config("/etc/app/config.yaml");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
✅ 适合:
#include <signal.h>
#include <iostream>
void reload(int) {
std::cout << "reload config" << std::endl;
}
int main() {
signal(SIGUSR1, reload);
while (true) {
// main loop
}
}
kill -USR1 <pid>
✅ 常用于:
如果是大型系统:
| 方案 | 说明 |
|---|---|
| etcd | 配置变更 watch |
| Consul | KV + watch |
| ZooKeeper | 节点监听 |
| Redis pub/sub | 配置推送 |
C++ 可:
| 场景 | 推荐 |
|---|---|
| 单机服务 | inotify + reload |
| 多进程 | inotify + SIGHUP |
| 分布式 | etcd / Consul |
| 简单脚本 | mtime 轮询 |
我可以给你完整可编译示例。