溫馨提示×

如何使用C++進行Linux系統監控

小樊
48
2025-04-22 05:06:42
欄目: 編程語言

在Linux系統中,可以使用C++編寫程序來監控系統的各種資源和性能指標。以下是一些常用的方法和庫,以及一個簡單的示例代碼,展示如何使用C++進行Linux系統監控。

常用方法和庫

  1. 讀取/proc文件系統

    • /proc/stat:提供CPU使用情況。
    • /proc/meminfo:提供內存使用情況。
    • /proc/diskstats:提供磁盤I/O統計信息。
    • /proc/net/dev:提供網絡接口的統計信息。
  2. 使用sysconf函數

    • 可以獲取系統配置參數,如系統內存大小等。
  3. 使用getrusage函數

    • 獲取當前進程的資源使用情況。
  4. 使用第三方庫

    • libstatgrab:一個跨平臺的系統監控庫。
    • Boost.Process:用于啟動和管理外部進程。

示例代碼:監控CPU和內存使用情況

以下是一個簡單的C++程序,展示如何讀取/proc/stat/proc/meminfo文件來獲取CPU和內存的使用情況。

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

std::string get_cpu_usage() {
    std::ifstream cpu_stat("/proc/stat");
    std::string line;
    std::getline(cpu_stat, line);
    std::istringstream iss(line);
    std::string cpu;
    iss >> cpu; // Skip "cpu"

    unsigned long long user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice;
    iss >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice;

    unsigned long long total = user + nice + system + idle + iowait + irq + softirq + steal;
    unsigned long long idle_time = idle + iowait;

    // Calculate CPU usage percentage
    static unsigned long long last_total = 0, last_idle = 0;
    unsigned long long total_diff = total - last_total;
    unsigned long long idle_diff = idle_time - last_idle;
    double cpu_usage = (total_diff - idle_diff) * 100.0 / total_diff;

    last_total = total;
    last_idle = idle_time;

    return std::to_string(cpu_usage) + "%";
}

std::string get_memory_usage() {
    std::ifstream mem_info("/proc/meminfo");
    std::string line;
    std::string key;
    unsigned long long total_mem, free_mem, buff_mem, cache_mem;

    while (std::getline(mem_info, line)) {
        std::istringstream iss(line);
        iss >> key >> total_mem >> free_mem >> buff_mem >> cache_mem;
        if (key == "MemTotal:") {
            break;
        }
    }

    unsigned long long used_mem = total_mem - free_mem - buff_mem - cache_mem;
    double memory_usage = (static_cast<double>(used_mem) / total_mem) * 100.0;

    return std::to_string(memory_usage) + "%";
}

int main() {
    while (true) {
        std::cout << "CPU Usage: " << get_cpu_usage() << std::endl;
        std::cout << "Memory Usage: " << get_memory_usage() << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    return 0;
}

編譯和運行

使用以下命令編譯和運行程序:

g++ -o monitor monitor.cpp
./monitor

這個程序會每秒輸出一次CPU和內存的使用情況。你可以根據需要擴展這個程序,添加更多的監控功能,比如磁盤I/O、網絡流量等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女