#ifndef _SYS_FUNC_H_
#define _SYS_FUNC_H_
int GetMemInfo(int *pTotal, int *pUsed);
int GetCpuUsedRate(int *pValue);
#endif
#include "sys_func.h"
#include <stdio.h>
#include<unistd.h>
#include <string.h>
#include <stdlib.h>
typedef struct //定义一个cpu occupy的结构体
{
char name[20]; //定义一个char类型的数组名name有20个元素
unsigned int user; //定义一个无符号的int类型的user
unsigned int nice; //定义一个无符号的int类型的nice
unsigned int system; //定义一个无符号的int类型的system
unsigned int idle; //定义一个无符号的int类型的idle
} CPU_OCCUPY;
typedef struct //定义一个mem occupy的结构体
{
char name[20]; //定义一个char类型的数组名name有20个元素
unsigned long total;
char name2[20];
unsigned long free;
} MEM_OCCUPY;
int cal_cpuoccupy (CPU_OCCUPY *o, CPU_OCCUPY *n)
{
unsigned long od, nd;
unsigned long id, sd;
int cpu_use = 0;
od = (unsigned long) (o->user + o->nice + o->system +o->idle);//第一次(用户+优先级+系统+空闲)的时间再赋给od
nd = (unsigned long) (n->user + n->nice + n->system +n->idle);//第二次(用户+优先级+系统+空闲)的时间再赋给od
id = (unsigned long) (n->user - o->user); //用户第一次和第二次的时间之差再赋给id
sd = (unsigned long) (n->system - o->system);//系统第一次和第二次的时间之差再赋给sd
if((nd-od) != 0)
cpu_use = (int)((sd+id)*10000)/(nd-od); //((用户+系统)乖100)除(第一次和第二次的时间差)再赋给g_cpu_used
else cpu_use = 0;
//printf("cpu: %u\n",cpu_use);
return cpu_use;
}
void get_cpuoccupy (CPU_OCCUPY *cpust) //对无类型get函数含有一个形参结构体类弄的指针O
{
FILE *fd;
int n;
char buff[256];
CPU_OCCUPY *cpu_occupy;
cpu_occupy=cpust;
fd = fopen ("/proc/stat", "r");
fgets (buff, sizeof(buff), fd);
sscanf (buff, "%s %u %u %u %u", cpu_occupy->name, &cpu_occupy->user, &cpu_occupy->nice,&cpu_occupy->system, &cpu_occupy->idle);
fclose(fd);
}
int GetCpuUsedRate(int *pValue)
{
if (NULL == pValue)
{
return -1;
}
CPU_OCCUPY cpu_stat1;
CPU_OCCUPY cpu_stat2;
//第一次获取cpu使用情况
get_cpuoccupy((CPU_OCCUPY *)&cpu_stat1);
usleep(100*1000);
//第二次获取cpu使用情况
get_cpuoccupy((CPU_OCCUPY *)&cpu_stat2);
//计算cpu使用率
int cpu = cal_cpuoccupy ((CPU_OCCUPY *)&cpu_stat1, (CPU_OCCUPY *)&cpu_stat2);
*pValue = cpu;
printf("===========CPU RATE:%d====\n", *pValue);
return 0;
}
int GetMemInfo(int *pTotal, int *pUsed)
{
if (NULL == pTotal || NULL == pUsed)
{
return -1;
}
char str[81] = {0};
FILE *fp;
memset(str, 0, sizeof(str));
fp = popen("cat /proc/meminfo | grep MemTotal | awk '{print $2}'", "r");
if (fp == NULL)
{
printf("获取系统mem信息失败!\n");
return -1;
}
fgets(str, 80, fp);
fclose(fp);
printf("GetMemorySize str = %s\n", str);
int nTotalSize = atoi(str)/1024;
printf("mem size = %d MByte\n", nTotalSize);
*pTotal = nTotalSize;
memset(str, 0, sizeof(str));
fp = popen("cat /proc/meminfo | grep MemAvailable | awk '{print $2}'", "r");
if (fp == NULL)
{
printf("获取系统mem信息失败!\n");
return -1;
}
fgets(str, 80, fp);
fclose(fp);
int nAvailbleSize = atoi(str)/1024;
printf("mem nAvailbleSize size = %d MByte\n", nAvailbleSize);
*pTotal = nTotalSize;
*pUsed = nTotalSize - nAvailbleSize;
printf("====pTotal:%d pFree:%d====\n", *pTotal, *pUsed);
return 0;
}