温馨提示×

linux c++配置怎么监控

小樊
36
2026-09-20 10:07:13
栏目: 编程语言

在 Linux + C++ 环境下,“配置怎么监控”通常有两种理解:

  1. 监控程序运行时的配置(参数、状态)
  2. 监控配置文件变化(如 yaml/json/conf 被修改)

下面分别说常见做法,给你可直接用的方案。


一、监控配置文件变化(最常见)

✅ 方案 1:inotify(Linux 原生,推荐)

适合监控:

  • .conf
  • .yaml
  • .json
  • 任意配置文件

示例(C++ + inotify)

#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;
            // 重新加载配置
        }
    }
}

✅ 优点:

  • 实时
  • 内核级
  • 不轮询

✅ 方案 2:文件 mtime 轮询(简单粗暴)

#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));
    }
}

✅ 适合:

  • 简单程序
  • 秒级延迟可接受

二、运行时配置监控(程序内部)

✅ 方案 3:信号触发重新加载(生产常用)

#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>

✅ 常用于:

  • Nginx
  • 自建服务
  • 守护进程

三、配置中心 / 高级方案

如果是大型系统:

方案 说明
etcd 配置变更 watch
Consul KV + watch
ZooKeeper 节点监听
Redis pub/sub 配置推送

C++ 可:

  • etcd-cpp-apiv3
  • librocketmq / redis++

四、推荐组合(实战)

场景 推荐
单机服务 inotify + reload
多进程 inotify + SIGHUP
分布式 etcd / Consul
简单脚本 mtime 轮询

五、如果你能补充这些,我可以给更精准方案

  • 配置是文件还是内存?
  • C++ 用什么框架(裸 C++ / Boost / gRPC)?
  • 是否需要热更新?
  • 是否容器 / Kubernetes?

我可以给你完整可编译示例。

0 踩