|
本帖最后由 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温度、内存信息、磁盘空间以及网卡信息。请注意,这只是一个入门示例,您可以根据需要进一步扩展和优化。
|
|