溫馨提示×

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

小樊
50
2025-09-15 06:19:52
欄目: 編程語言

在Linux中使用C++進行系統監控,可以通過多種方式實現。以下是一些常見的方法:

  1. 讀取/proc文件系統: Linux的/proc文件系統提供了關于系統和進程的實時信息。你可以編寫C++程序來讀取這些文件,獲取CPU使用率、內存使用情況、磁盤I/O統計等信息。

  2. 使用sysfs接口: sysfs是一個虛擬文件系統,它提供了對內核數據結構的訪問。通過sysfs,你可以獲取硬件和驅動程序的信息。

  3. 調用系統命令: 你可以使用C++中的system()函數或者更高級的popen()函數來執行系統命令(如top, df, free, iostat等),然后解析它們的輸出。

  4. 使用Linux性能計數器(perf)API: perf是Linux內核提供的一個強大的性能分析工具。它的API可以用來收集各種硬件和軟件的性能事件。

  5. 使用第三方庫: 有一些第三方庫可以幫助你更容易地進行系統監控,例如libstatgrab、libsysinfo等。

下面是一個簡單的例子,展示如何使用C++讀取/proc/stat文件來獲取CPU的使用情況:

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

std::vector<std::string> split(const std::string &s, char delimiter) {
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(s);
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

int main() {
    std::ifstream statFile("/proc/stat");
    std::string line;
    if (statFile.is_open()) {
        while (std::getline(statFile, line)) {
            if (line.substr(0, 3) == "cpu") {
                std::vector<std::string> cpuStats = split(line, ' ');
                // The first value is "cpu", so we start from the second one
                unsigned long long userTime = std::stoull(cpuStats[1]);
                unsigned long long niceTime = std::stoull(cpuStats[2]);
                unsigned long long systemTime = std::stoull(cpuStats[3]);
                unsigned long long idleTime = std::stoull(cpuStats[4]);
                unsigned long long iowait = std::stoull(cpuStats[5]);
                unsigned long long irq = std::stoull(cpuStats[6]);
                unsigned long long softirq = std::stoull(cpuStats[7]);
                unsigned long long steal = std::stoull(cpuStats[8]);

                // Calculate total idle and total non-idle time
                unsigned long long totalIdle = idleTime + iowait;
                unsigned long long totalNonIdle = userTime + niceTime + systemTime + irq + softirq + steal;

                // For simplicity, we just print the raw values
                std::cout << "User time: " << userTime << std::endl;
                std::cout << "Nice time: " << niceTime << std::endl;
                std::cout << "System time: " << systemTime << std::endl;
                std::cout << "Idle time: " << idleTime << std::endl;
                std::cout << "IOWait: " << iowait << std::endl;
                std::cout << "IRQ: " << irq << std::endl;
                std::cout << "SoftIRQ: " << softirq << std::endl;
                std::cout << "Steal: " << steal << std::endl;
                std::cout << "Total idle: " << totalIdle << std::endl;
                std::cout << "Total non-idle: " << totalNonIdle << std::endl;

                // Calculate CPU usage since last check
                // Note: This is a very simplistic approach and not accurate for multiple checks
                static unsigned long long lastTotalIdle = 0;
                static unsigned long long lastTotalNonIdle = 0;
                unsigned long long totalDiff = totalIdle + totalNonIdle - lastTotalIdle - lastTotalNonIdle;
                unsigned long long idleDiff = totalIdle - lastTotalIdle;
                double cpuUsage = (totalDiff - idleDiff) * 100.0 / totalDiff;
                std::cout << "CPU Usage: " << cpuUsage << "%" << std::endl;

                lastTotalIdle = totalIdle;
                lastTotalNonIdle = totalNonIdle;
                break; // We only want to read the CPU stats once
            }
        }
        statFile.close();
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    return 0;
}

請注意,這個例子非?;A,實際的系統監控程序可能需要處理更多的邊緣情況,并且可能需要定期采樣以計算更準確的CPU使用率。此外,對于更復雜的監控任務,可能需要使用更高級的工具和庫。

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