#include <stdio.h>
#include<stdlib.h>
#define uint unsigned int
#define N 20
typedef struct{
char cpu[10];
uint user_t;
uint nice_t;
uint system_t;
uint idel_t;
uint iowait_t;
uint irq_t;
uint sirq_t;
}CPU;
struct sysinfo {
long uptime; /* Seconds since boot */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
unsigned long totalram; /* Total usable main memory size */
unsigned long freeram; /* Available memory size */
unsigned long sharedram; /* Amount of shared memory */
unsigned long bufferram; /* Memory used by buffers */
unsigned long totalswap; /* Total swap space size */
unsigned long freeswap; /* swap space still available */
unsigned short procs; /* Number of current processes */
char _f[22]; /* Pads structure to 64 bytes */
};
int get_cpu(CPU op[] );//获取cpu _i的在stat值
float cpul(CPU op1[],CPU op2[]);//计算利用率
int getmen(struct sysinfo *info);//获取内存值
int main(int argc,const char *argv[])
{
CPU op1[N],op2[N];
struct sysinfo info;
int i=0,j=0;
//float cpu;
while(1){
get_cpu(op1);
sleep(1);
get_cpu(op2);
system("clear");
cpul(op1,op2);
getmen(&info);
printf("tatal men: %ld\t free mem: %ld\ntotal swap: %ld\t free swap:%ld\n\n",info.totalram/1024,info.freeram/1024,info.totalswap/1024,info.freeswap/1024);
}
return 0;
}
int get_cpu(CPU op1[]){//向函数中传入CUP数组
FILE *fp;
char buf[100];
int i=0;
CPU op;
//proc/stat
fp = fopen("/proc/stat","r");//只是打开文件,得到地址
while(1){
fgets(buf,100,fp);//获取一行
sscanf(buf,"%s %d %d %d %d %d %d %d",
op.cpu,&op.user_t,&op.nice_t,&op.system_t,
&op.idel_t,&op.iowait_t,&op.irq_t,&op.sirq_t);
op1[i] = op;
i++;
if(op.cpu[0] != 'c' || op.cpu[1] != 'p' )
{
fclose(fp);
break;
}
}
return 0;
}
float cpul(CPU op1[],CPU op2[]){
float t1,t2,u1,u2;
float cpul;
int i=0;
while(1){
t1 = op1[i].user_t + op1[i].nice_t + op1[i].system_t +
op1[i].idel_t + op1[i].iowait_t + op1[i].irq_t + op1[i].sirq_t;
t2 = op2[i].user_t + op2[i].nice_t + op2[i].system_t +
op2[i].idel_t + op2[i].iowait_t + op2[i].irq_t + op2[i].sirq_t;
u1= op1[i].user_t + op1[i].nice_t + op1[i].system_t;
u2 = op2[i].user_t + op2[i].nice_t + op2[i].system_t;
printf("%s:",op1[i].cpu);
if(t2 - t1 == 0)
cpul = 0;
else
cpul = (u2 - u1) / (t2 - t1);
printf("%f\n",cpul);
i++;
if(op1[i].cpu[0] != 'c' || op1[i].cpu[1] != 'p' )
break;
}
}
int getmen(struct sysinfo *info){
sysinfo(info);
}
05-23
6919
04-10
1316
08-17
3544