Skip to main content

System monitoring using C++

 System monitoring using C++ 

The description "system monitoring using C++" refers to the practice of developing software applications or tools in the C++ programming language to monitor and collect data from a computer system or network. System monitoring is crucial for maintaining the health, performance, and security of computer systems, servers, and networks. 

System monitoring using C++ involves the development of software applications, utilities, or scripts in the C++ programming language to actively track, collect, and analyze various metrics and data from computer systems, servers, or networks. These metrics can include CPU usage, memory usage, disk space, network traffic, hardware status, and other relevant information that allows administrators and developers to gain insights into the system's behavior.

C++ is a powerful and efficient programming language well-suited for system monitoring due to its performance characteristics and the ability to interact with low-level system resources. When monitoring systems using C++, developers can create custom monitoring tools or integrate with existing monitoring solutions to keep a watchful eye on system performance, detect anomalies, and ensure that systems are operating optimally.

System monitoring using C++ can encompass a wide range of functionalities, including real-time data collection, data visualization, alerting, historical data analysis, and the ability to respond to and mitigate issues or anomalies as they occur. Such monitoring is essential for ensuring system availability, identifying and addressing performance bottlenecks, and even detecting and responding to security threats.

Whether you are developing monitoring solutions for your own infrastructure or creating commercial software for system administrators, system monitoring using C++ can provide the flexibility and control needed to tailor your monitoring tools to the specific needs of your systems and users.

Github Link:

https://github.com/Sivatech24/SystemMonitoringUsingCPlusPlus.git

Measure Memory Usage Code:

#include <iostream>

#include <fstream>

#include <string>

#include <sstream>

// Function to retrieve memory usage in kilobytes

long getMemoryUsageKB() {

    std::stringstream ss;

    std::ifstream statusFile("/proc/self/status");

    if (!statusFile) {

        std::cerr << "Failed to open status file." << std::endl;

        return -1;

    }


    std::string line;

    while (std::getline(statusFile, line)) {

        if (line.compare(0, 7, "VmSize:") == 0) {

            long memorySizeKB;

            std::istringstream ss(line.substr(7));

            ss >> memorySizeKB;

            return memorySizeKB;

        }

    }


    return -1; // Memory usage not found

}


int main() {

    long memoryUsageKB = getMemoryUsageKB();

    if (memoryUsageKB != -1) {

        std::cout << "Memory Usage: " << memoryUsageKB << " KB" << std::endl;

    } else {

        std::cerr << "Failed to retrieve memory usage." << std::endl;

    }


    return 0;

}

Measure RAM Usage Code:

#include <iostream>

#include <fstream>

#include <string>

#include <sstream>

// Function to retrieve RAM usage in kilobytes

long getRAMUsageKB() {

    std::stringstream ss;

    std::ifstream meminfoFile("/proc/meminfo");

    if (!meminfoFile) {

        std::cerr << "Failed to open meminfo file." << std::endl;

        return -1;

    }


    std::string line;

    while (std::getline(meminfoFile, line)) {

        if (line.find("MemTotal:") == 0) {

            long totalMemoryKB;

            std::istringstream ss(line.substr(10));

            ss >> totalMemoryKB;

            return totalMemoryKB;

        }

    }


    return -1; // RAM usage not found

}


int main() {

    long totalRAMKB = getRAMUsageKB();

    if (totalRAMKB != -1) {

        std::cout << "Total RAM: " << totalRAMKB << " KB" << std::endl;

    } else {

        std::cerr << "Failed to retrieve RAM usage." << std::endl;

    }


    return 0;

}

Monitoring CPU code:

#include <iostream>

#include <windows.h>


int main() {

    ULONGLONG prevIdleTime = 0, prevKernelTime = 0, prevUserTime = 0;


    while (true) {

        FILETIME idleTime, kernelTime, userTime;

        if (GetSystemTimes(&idleTime, &kernelTime, &userTime)) {

            ULONGLONG idle = ((reinterpret_cast<ULARGE_INTEGER*>(&idleTime))->QuadPart - prevIdleTime);

            ULONGLONG kernel = ((reinterpret_cast<ULARGE_INTEGER*>(&kernelTime))->QuadPart - prevKernelTime);

            ULONGLONG user = ((reinterpret_cast<ULARGE_INTEGER*>(&userTime))->QuadPart - prevUserTime);


            double total = static_cast<double>(kernel + user);

            double cpuUsage = 100.0 - (static_cast<double>(idle) / total * 100.0);


            std::cout << "CPU Usage: " << cpuUsage << "%" << std::endl;


            prevIdleTime = (reinterpret_cast<ULARGE_INTEGER*>(&idleTime))->QuadPart;

            prevKernelTime = (reinterpret_cast<ULARGE_INTEGER*>(&kernelTime))->QuadPart;

            prevUserTime = (reinterpret_cast<ULARGE_INTEGER*>(&userTime))->QuadPart;

        }


        // You can add memory and GPU monitoring here

        // Memory monitoring may involve platform-specific code or libraries.

        // GPU monitoring typically requires vendor-specific libraries or APIs.


        Sleep(1000); // Sleep for 1 second

    }


    return 0;

}

Output:



Monitoring NVIDIA GPU Code:

#include <iostream>

#include <nvml.h>


int main() {

    nvmlReturn_t result;

    result = nvmlInit();


    if (result != NVML_SUCCESS) {

        std::cerr << "Failed to initialize NVML: " << nvmlErrorString(result) << std::endl;

        return 1;

    }


    int deviceCount;

    result = nvmlDeviceGetCount(&deviceCount);


    if (result != NVML_SUCCESS) {

        std::cerr << "Failed to query device count: " << nvmlErrorString(result) << std::endl;

        nvmlShutdown();

        return 1;

    }


    for (int i = 0; i < deviceCount; i++) {

        nvmlDevice_t device;

        result = nvmlDeviceGetHandleByIndex(i, &device);


        if (result != NVML_SUCCESS) {

            std::cerr << "Failed to get device handle: " << nvmlErrorString(result) << std::endl;

            continue;

        }


        char name[NVML_DEVICE_NAME_BUFFER_SIZE];

        result = nvmlDeviceGetName(device, name, NVML_DEVICE_NAME_BUFFER_SIZE);


        if (result == NVML_SUCCESS) {

            std::cout << "GPU " << i << " Name: " << name << std::endl;

        }


        nvmlUtilization_t utilization;

        result = nvmlDeviceGetUtilizationRates(device, &utilization);


        if (result == NVML_SUCCESS) {

            std::cout << "GPU " << i << " Utilization (GPU/VRAM): " << utilization.gpu << "% / " << utilization.memory << "%" << std::endl;

        }

    }


    nvmlShutdown();

    return 0;

}

Resource Monitoring Code:

#include <iostream>

#include <fstream>

#include <string>

#include <chrono>

#include <thread>

#include <sstream>

void monitorResources() {

    while (true) {

        std::stringstream ss;

        std::ifstream statFile("/proc/stat");

        std::ifstream meminfoFile("/proc/meminfo");


        if (!statFile || !meminfoFile) {

            std::cerr << "Failed to open resource files." << std::endl;

            return;

        }


        std::string line;

        double cpuUsage = 0.0;

        long totalMemory = 0, freeMemory = 0;


        // Parse CPU usage

        while (std::getline(statFile, line) && line.compare(0, 3, "cpu") == 0) {

            std::istringstream ss(line);

            std::string cpu;

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

            ss >> cpu >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice;


            if (cpu == "cpu") {

                // Calculate CPU usage percentage

                long prevIdle = idle + iowait;

                std::this_thread::sleep_for(std::chrono::milliseconds(1000));

                std::getline(statFile, line);

                ss.clear();

                ss.str(line);

                ss >> cpu >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice;


                long idleTime = idle + iowait - prevIdle;

                long totalTime = user + nice + system + idle + iowait + irq + softirq + steal;

                cpuUsage = 100.0 * (totalTime - idleTime) / totalTime;

                break;

            }

        }


        // Parse memory usage

        while (std::getline(meminfoFile, line)) {

            if (line.find("MemTotal:") == 0) {

                std::istringstream ss(line);

                std::string label;

                ss >> label >> totalMemory;

            }

            else if (line.find("MemFree:") == 0) {

                std::istringstream ss(line);

                std::string label;

                ss >> label >> freeMemory;

            }

        }


        // Calculate used memory

        long usedMemory = totalMemory - freeMemory;


        std::cout << "CPU Usage: " << cpuUsage << "%" << std::endl;

        std::cout << "Used Memory: " << usedMemory / 1024 << " KB" << std::endl;


        std::this_thread::sleep_for(std::chrono::seconds(1)); // Sleep for 1 second

    }

}


int main() {

    monitorResources();

    return 0;

}

Thank You For Visiting Our Blog.

Comments

Popular posts from this blog

Install TensorFlow on Windows 11: Step-by-Step Guide for CPU & GPU

 --- Installing **TensorFlow on Windows 11** requires setting up system dependencies, configuring Python, and ensuring compatibility with CPU or GPU acceleration. This step-by-step guide provides everything needed to install **TensorFlow 2.10 or lower** on **Windows Native**, including software prerequisites, Microsoft Visual C++ Redistributable installation, Miniconda setup, GPU driver configuration, and verification steps.   ### **System Requirements:**   Before installing TensorFlow, ensure your system meets these requirements:   - **Operating System:** Windows 7 or higher (64-bit)   - **Python Version:** 3.9–3.12   - **pip Version:** 19.0 or higher for Linux and Windows, 20.3 or higher for macOS   - **Microsoft Visual C++ Redistributable:** Required for Windows Native   - **Long Paths Enabled:** Ensure long paths are enabled in Windows settings   For **GPU support**, install:   - **NVIDIA ...

Cloudflare Is Down Worldwide: What Happened, What It Means & What You Can Do

๐ŸŒ Cloudflare Is Down Worldwide: What Happened & Why the Internet Broke Today On 18 November 2025 , the internet experienced one of the largest global outages in years as Cloudflare , the backbone of countless websites and online services, went down unexpectedly. The outage caused millions of websites to become slow, unreachable, or return 5xx internal server errors , leading to widespread disruption across businesses, apps, and essential online platforms. This blog post explains what happened, why the internet broke for many users, and what Cloudflare has officially said so far. What Exactly Happened? Around 4:30 PM IST , reports began flooding social media and outage trackers like Downdetector. Users across India, Europe, the US, and Southeast Asia noticed that: Websites were not loading Requests were timing out Services dependent on Cloudflare CDN or DNS stopped responding APIs hosted through Cloudflare were failing Even some security and protection layers were ...

Unreal Engine Product Showcase: Mesmerizing Video Sequence Render

  4k Image: