使用c语言获取linux系统各个CPU核心的使用率
时间: 2024-03-27 15:39:09 浏览: 144
要获取Linux系统各个CPU核心的使用率,可以使用C语言编写程序,通过读取/proc/stat文件中的信息来获取。
下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_CPU_NUM 8 // 假设最多有8个CPU核心
int main() {
int i;
long int user1, nice1, sys1, idle1, iowait1, irq1, softirq1, steal1, guest1, guest_nice1;
long int user2, nice2, sys2, idle2, iowait2, irq2, softirq2, steal2, guest2, guest_nice2;
double usage[MAX_CPU_NUM];
while (1) {
// 读取/proc/stat文件,获取CPU的使用情况
FILE* fp = fopen("/proc/stat", "r");
if (fp == NULL) {
perror("fopen");
exit(1);
}
fscanf(fp, "cpu %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld\n",
&user1, &nice1, &sys1, &idle1, &iowait1, &irq1, &softirq1, &steal1, &guest1, &guest_nice1);
fclose(fp);
// 等待一段时间,再次读取/proc/stat文件,获取CPU的使用情况
sleep(1);
fp = fopen("/proc/stat", "r");
if (fp == NULL) {
perror("fopen");
exit(1);
}
fscanf(fp, "cpu %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld\n",
&user2, &nice2, &sys2, &idle2, &iowait2, &irq2, &softirq2, &steal2, &guest2, &guest_nice2);
fclose(fp);
// 计算每个CPU核心的使用率
for (i = 0; i < MAX_CPU_NUM; i++) {
double total1 = user1 + nice1 + sys1 + idle1 + iowait1 + irq1 + softirq1 + steal1 + guest1 + guest_nice1;
double total2 = user2 + nice2 + sys2 + idle2 + iowait2 + irq2 + softirq2 + steal2 + guest2 + guest_nice2;
double idle_delta = idle2 - idle1;
double total_delta = total2 - total1;
usage[i] = 100.0 * (1.0 - idle_delta / total_delta);
user1 = user2;
nice1 = nice2;
sys1 = sys2;
idle1 = idle2;
iowait1 = iowait2;
irq1 = irq2;
softirq1 = softirq2;
steal1 = steal2;
guest1 = guest2;
guest_nice1 = guest_nice2;
}
// 输出每个CPU核心的使用率
for (i = 0; i < MAX_CPU_NUM; i++) {
printf("CPU%d usage: %.2f%%\n", i, usage[i]);
}
printf("\n");
}
return 0;
}
```
这个程序会不断循环读取/proc/stat文件,计算每个CPU核心的使用率,并输出结果。注意,程序中假设最多有8个CPU核心,如果实际系统中CPU核心数不足8个,可以根据实际情况修改代码。
阅读全文