#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
//#include <thread>
typedef struct CPU_PACKED
{
char name[20];
unsigned int user;
unsigned int nice;
unsigned int system;
unsigned int idle;
}CPU_OCCUPY;
//-----------------------mem--------------------
typedef struct MEM_PACKED
{
char name[20];
unsigned long total;
char name2[20];
}MEM_OCCUPY;
typedef struct MEM_PACK
{
double total;
double used_rate;
}MEM_PACK;
//------------------------------sysinfo-------------
/**
struct sysinfo{
long uptime;
unsigned long totalram;
};
*/
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);//第一次(用户+优先级+系统+空闲)的时间
nd = (unsigned long) (n->user + n->nice + n->system + n->idle); //第二次
id = (unsigned long) (n->user - o->user);
sd = (unsigned long) (n->system - o->system);
if((nd - od) != 0){
cpu_use = (int)((sd+id)*100)/(nd-od);
}else {
cpu_use = 0;
}
return cpu_use;
}
void get_cpuoccupy(CPU_OCCUPY *cpust)
{
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);
}
MEM_PACK get_memocupy()
{
FILE *fd;
int n;
double mem_total,mem_used_rate;
char buff[256];
MEM_OCCUPY *m = (MEM_OCCUPY*)malloc(sizeof(MEM_OCCUPY));
MEM_PACK p;
fd = fopen("/proc/meminfo", "r");
fgets(buff,sizeof (buff), fd);
sscanf(buff, "%s %lu %s\n", m->name, &m->total, m->name2);
mem_total = m->total;
fgets(buff,sizeof (buff),fd);
sscanf(buff, "%s %lu %s\n", m->name, &m->total,m->name2);
mem_used_rate = (1 - m->total/mem_total)*100;
mem_total = mem_total/(1024*1024);
p.total = mem_total;
p.used_rate = mem_used_rate;
fclose(fd);
free(m);
return p;
}
int get_cpu_temp()
{
FILE *fd;
int temp;
char buff[256];
fd = fopen("/sys/class/thermal/thermal_zone0/temp","r");
fgets(buff,sizeof(buff),fd);
sscanf(buff, "%d", &temp);
fclose(fd);
return temp/1000;
}
int get_last_reboot(char *cmd,char *output, int size)
{
FILE *fp = NULL;
fp = popen(cmd,"r");
if(fp){
fgets(output,size,fp);
if(fgets(output,size,fp) != NULL){
if(output[strlen(output) - 1] == '\n')
output[strlen(output) - 1] = '\0';
}
pclose(fp);
}
return 0;
}
int main()
{
CPU_OCCUPY cpu_stat1;
CPU_OCCUPY cpu_stat2;
int cpu;
int temp = get_cpu_temp();
printf("cpu temperature is %d\n",temp);
struct MEM_PACK mem = get_memocupy();
printf("mem occupy total %f use_rate %f\n",mem.total,mem.used_rate);
char lastreboot[64];
while(1){
get_last_reboot("last reboot",lastreboot, 64);
printf("%s \n",lastreboot);
get_cpuoccupy((CPU_OCCUPY*)&cpu_stat1);
usleep(10000);
get_cpuoccupy((CPU_OCCUPY*)&cpu_stat2);
cpu = cal_cpuoccupy((CPU_OCCUPY *)&cpu_stat1,(CPU_OCCUPY*)&cpu_stat2);
printf("cpu usage: %d \n",cpu);
usleep(1000000);
}
return 0;
}
linux C编程 获取 CPU温度 使用率,内存使用率 开机时间信息
最新推荐文章于 2024-08-17 11:36:20 发布