找回密码
 立即注册
查看: 1983|回复: 0

树莓派基于C语言获取系统资源信息

[复制链接]

86

主题

0

回帖

894

积分

中级会员

积分
894
发表于 2024-4-22 16:58:03 | 显示全部楼层 |阅读模式
本帖最后由 Cryyen 于 2024-4-22 17:04 编辑

在树莓派上使用C语言读取系统资源信息,包括CPU、内存、磁盘、网卡等,您可以通过读取特定文件或者调用系统命令来获取这些信息。以下是一个基本的示例,演示如何读取CPU温度、内存使用、磁盘空间以及网卡信息。
#include <stdio.h>


void readCPUTemperature() {
    FILE *temperatureFile;
    float cpuTemperature;


    // 打开CPU温度文件
    temperatureFile = fopen("/sys/class/thermal/thermal_zone0/temp", "r");


    if (temperatureFile == NULL) {
        perror("Error opening temperature file");
        return;
    }


    // 读取CPU温度
    fscanf(temperatureFile, "%f", &cpuTemperature);


    // 关闭文件
    fclose(temperatureFile);


    // 打印CPU温度
    printf("CPU Temperature: %.2f°C\n", cpuTemperature / 1000.0);
}


void readMemoryInfo() {
    FILE *memoryFile;
    unsigned long totalMemory, freeMemory, bufferMemory;


    // 打开内存信息文件
    memoryFile = fopen("/proc/meminfo", "r");


    if (memoryFile == NULL) {
        perror("Error opening memory file");
        return;
    }


    // 读取内存信息
    fscanf(memoryFile, "MemTotal: %lu kB", &totalMemory);
    fscanf(memoryFile, "MemFree: %lu kB", &freeMemory);
    fscanf(memoryFile, "Buffers: %lu kB", &bufferMemory);


    // 关闭文件
    fclose(memoryFile);


    // 计算已使用内存
    unsigned long usedMemory = totalMemory - freeMemory - bufferMemory;


    // 打印内存信息
    printf("Total Memory: %lu kB\n", totalMemory);
    printf("Used Memory: %lu kB\n", usedMemory);
    printf("Free Memory: %lu kB\n", freeMemory);
}


void readDiskSpace() {
    FILE *dfCommand;
    char buffer[128];


    // 执行系统命令并获取输出
    dfCommand = popen("df -h", "r");


    if (dfCommand == NULL) {
        perror("Error executing df command");
        return;
    }


    // 读取命令输出
    while (fgets(buffer, sizeof(buffer), dfCommand) != NULL) {
        printf("%s", buffer);
    }


    // 关闭文件
    pclose(dfCommand);
}


void readNetworkInfo() {
    FILE *ifconfigCommand;
    char buffer[128];


    // 执行系统命令并获取输出
    ifconfigCommand = popen("ifconfig", "r");


    if (ifconfigCommand == NULL) {
        perror("Error executing ifconfig command");
        return;
    }


    // 读取命令输出
    while (fgets(buffer, sizeof(buffer), ifconfigCommand) != NULL) {
        printf("%s", buffer);
    }


    // 关闭文件
    pclose(ifconfigCommand);
}


int main() {
    printf("System Resource Information:\n");


    printf("\nCPU Information:\n");
    readCPUTemperature();


    printf("\nMemory Information:\n");
    readMemoryInfo();


    printf("\nDisk Space Information:\n");
    readDiskSpace();


    printf("\nNetwork Information:\n");
    readNetworkInfo();


    return 0;
}


此示例演示了如何使用C语言读取树莓派上的CPU温度、内存信息、磁盘空间以及网卡信息。请注意,这只是一个入门示例,您可以根据需要进一步扩展和优化。


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|EnMaking

GMT+8, 2025-3-28 10:31 , Processed in 0.052894 second(s), 22 queries .

Powered by Qiqirobot

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表