linux get memory and cpu occupy

#include <iostream>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

class MxcSysInfo{
public:
    typedef struct CPUPACKED{
        char name[20];
        unsigned int user;
        unsigned int nice;
        unsigned int sys;
        unsigned int idle;
        unsigned int iowait;
        unsigned int irq;
        unsigned int softirq;
    }CPU_OCCUPY;

    typedef struct MEMPACKED{
        char nameTotal[20];
        unsigned int total;
        char nameFree[20];
        unsigned int free;
        char nameAvailable[20];
        unsigned int available;
    }MEM_OCCUPY;


	static float getTotalMemPercent();
	static float getProcessMemPercent(const pid_t p);
	static float getProcessMemPercent(const char* ProcessName);
	static unsigned int getProcessMem(const pid_t p);
	static unsigned int getProcessMem(const char* ProcessName);
	static unsigned int getTotalMem();

	static float getTotalCpuPercent();
	static float getProcessCpuPercent(const pid_t p);
	static float getProcessCpuPercent(const char* ProcessName);

	static pid_t pidof(const char* ProcessName);

private:
	static int get_memoccupy(MxcSysInfo::MEM_OCCUPY* mem);
	static int get_cpuoccupy(MxcSysInfo::CPU_OCCUPY* mem);
	static char *get_items(const char *buffer, int ie);

	//cpu
	static unsigned int get_cpu_process_occupy(const pid_t p);
	static unsigned int get_cpu_total_occupy();
	static unsigned int get_cpu_core_number();
	static unsigned int get_cpu_core_useage();

	//mem
	static unsigned int get_phy_mem(const pid_t p);   //获取进程占用物理内存
	static unsigned int get_total_mem();
	static unsigned int get_phy_total_pages();
	static unsigned int get_phy_available_pages();
};

//cpp
#include <fstream>
#include <sstream>
#include <iomanip>
#include "libsysinfo.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int MxcSysInfo::get_memoccupy(MxcSysInfo::MEM_OCCUPY *mem)
{
	FILE *pf;
	int n;
	char buff[256];
	char temp[20];
	MxcSysInfo::MEM_OCCUPY *m = mem;

	pf = fopen ("/proc/meminfo", "r");
	if(pf == NULL)
		return -1;

	char *pstatus = NULL;
	pstatus = fgets (buff, sizeof(buff), pf);
	if( pstatus == NULL )
	{
		fclose(pf);
		return -1;
	}

	if(sscanf(buff, "%s %u %s", m->nameTotal, &m->total, temp) != 3)
	{
		fclose(pf);
		return -1;
	}

	pstatus = fgets (buff, sizeof(buff), pf);
	if( pstatus == NULL )
	{
		fclose(pf);
		return -1;
	}

	if(sscanf(buff, "%s %u %s", m->nameFree, &m->free, temp) != 3)
	{
		fclose(pf);
		return -1;
	}

	pstatus = fgets (buff, sizeof(buff), pf);
	if( pstatus == NULL )
	{
		fclose(pf);
		return -1;
	}

	if(sscanf (buff, "%s %u %s", m->nameAvailable, &m->available, temp) !=3)
	{
		fclose(pf);
		return -1;
	}

	fclose(pf);
	return 0;
}


int MxcSysInfo::get_cpuoccupy(MxcSysInfo::CPU_OCCUPY *cpust)
{
	FILE *fd;
	int n;
	char buff[256];
	char *pstatus;
	MxcSysInfo::CPU_OCCUPY *cpu_occupy;
	cpu_occupy=cpust;

	fd = fopen("/proc/stat", "r");
	if(fd == NULL)
		return -1;

	pstatus =fgets(buff, sizeof(buff), fd);
	if(pstatus == NULL)
	{
		fclose(fd);
		return -1;
	}


	if(sscanf(buff, "%s %u %u %u %u %u %u %u", cpu_occupy->name
				,&cpu_occupy->user, &cpu_occupy->nice,&cpu_occupy->sys, &cpu_occupy->idle
				,&cpu_occupy->iowait, &cpu_occupy->irq,&cpu_occupy->softirq) != 8)
	{
		fclose(fd);
		return -1;

	}
	fclose(fd);
	return 0;
}

int cal_cpuoccupy(MxcSysInfo::CPU_OCCUPY *o, MxcSysInfo::CPU_OCCUPY *n)
{
	unsigned long od, nd;
	unsigned long id, sd;
	int cpu_use = 0;

	od = o->user + o->nice + o->sys + o->idle + o->iowait + o->irq + o->softirq;
	nd = n->user + n->nice + n->sys + n->idle + n->iowait + n->irq + n->softirq;

	id = n->user - o->user;
	sd = n->sys - o->sys;

	unsigned int idle = n->idle - o->idle;

	if ((nd-od) != 0)
		cpu_use = ((nd-od-(n->idle - o->idle))*10000)/(nd-od);
	else
		cpu_use = 0;
	return cpu_use;
}


float MxcSysInfo::getTotalCpuPercent()
{
	MxcSysInfo::CPU_OCCUPY o;
	MxcSysInfo::CPU_OCCUPY n;
	memset(&o, 0 , sizeof(MxcSysInfo::CPU_OCCUPY));
	memset(&n, 0 , sizeof(MxcSysInfo::CPU_OCCUPY));

	if(get_cpuoccupy(&o) < 0)
		return 0.0;

	usleep(1000*500);

	if(get_cpuoccupy(&n) < 0)
		return 0.0;

	return cal_cpuoccupy(&o, &n)/100.0;
}

float MxcSysInfo::getTotalMemPercent()
{
	MxcSysInfo::MEM_OCCUPY mem;
	memset(&mem, 0 , sizeof(mem));
	if(get_memoccupy(&mem)<0)
		return 0.0;
	return ((mem.total - mem.free)*10000 / mem.total)/100.0;
}


unsigned int MxcSysInfo::get_cpu_core_number()
{
	return sysconf(_SC_NPROCESSORS_CONF);
}

unsigned int MxcSysInfo::get_cpu_core_useage()
{
	return sysconf(_SC_NPROCESSORS_ONLN);
}

unsigned int MxcSysInfo::get_phy_total_pages()
{
	return sysconf(_SC_PHYS_PAGES);
}

unsigned int MxcSysInfo::get_phy_available_pages()
{
	return sysconf(_SC_AVPHYS_PAGES);
}

unsigned int MxcSysInfo::get_phy_mem(const pid_t p)
{

	char file[128] = {0};
	char line_buff[256] = {0};
	sprintf(file, "/proc/%d/status", p);

	FILE *pf;
	pf = fopen(file, "r");
	if(pf == NULL)
		return 0;

	char name[32];
	unsigned int vmrss;
	while(fgets(line_buff, sizeof(line_buff), pf) != NULL)
	{
		sscanf(line_buff, "%s %d", name, &vmrss);
		if (strcmp("VmRSS:", name) == 0)
		{
			fclose(pf);
			return vmrss;
		}
	}
	fclose(pf);
	return 0;
}

unsigned int MxcSysInfo::get_total_mem()
{
	char file[128] = {0};
	char line_buff[256] = {0};
	sprintf(file, "/proc/meminfo");

	FILE *pf;
	pf = fopen(file, "r");
	if(pf == NULL)
		return 0;

	char name[32];
	unsigned int MemTotal;
	while(fgets(line_buff, sizeof(line_buff), pf) != NULL)
	{
		sscanf(line_buff, "%s %d", name, &MemTotal);
		if (strcmp("MemTotal:", name) == 0)
		{
			fclose(pf);
			return MemTotal;
		}
	}
	fclose(pf);
	return 0;
}


float MxcSysInfo::getProcessMemPercent(const pid_t p)
{
	unsigned int  phymem = get_phy_mem(p);
	if(phymem == 0)
		return 0.0;
	unsigned int  totalmem = get_total_mem();
	if(totalmem == 0)
		return 0.0;
	//    return (phymem*1.0)/(totalmem*1.0) * 100;
	return ((phymem*10000)/totalmem) / 100.0;
}


float MxcSysInfo::getProcessMemPercent(const char* ProcessName)
{
	pid_t pid = pidof(ProcessName);
	if(pid < 0)
		return 0.0;
	return getProcessMemPercent(pid);
}


unsigned int MxcSysInfo::get_cpu_process_occupy(const pid_t p)
{
	char file[128] = {0};
	char line_buff[1024] = {0};
	sprintf(file, "/proc/%d/stat", p);

	FILE *pf;
	pf = fopen(file, "r");
	if( pf == NULL ) return 0;

	if( fgets(line_buff, sizeof(line_buff), pf) == NULL )
	{
		fclose(pf);
		return 0;
	}


	char* q = get_items(line_buff, 14);
	if(q==NULL) return 0;


	MxcSysInfo::CPU_OCCUPY cpu_occupy;
	memset(&cpu_occupy, 0 , sizeof(cpu_occupy));


	if(sscanf(q, "%u %u %u %u",&cpu_occupy.user, &cpu_occupy.nice,&cpu_occupy.sys, &cpu_occupy.idle) != 4)
	{
		fclose(pf);
		return 0;
	}

	fclose(pf);

	return (cpu_occupy.user + cpu_occupy.nice + cpu_occupy.sys + cpu_occupy.idle);
}

unsigned int MxcSysInfo::get_cpu_total_occupy()
{
	char line_buff[1024] = {0};
	FILE *pf;
	MxcSysInfo::CPU_OCCUPY cpu_occupy;

	pf = fopen("/proc/stat", "r");
	if(pf == NULL)
		return 0;

	if(fgets(line_buff, sizeof(line_buff), pf) == NULL)
	{
		fclose(pf);
		return 0;
	}

	if(sscanf(line_buff, "%s %u %u %u %u", cpu_occupy.name
				,&cpu_occupy.user, &cpu_occupy.nice
				,&cpu_occupy.sys, &cpu_occupy.idle) !=5)
	{
		fclose(pf);
		return 0;
	}

	fclose(pf);

	return (cpu_occupy.user + cpu_occupy.nice + cpu_occupy.sys + cpu_occupy.idle);
}

float MxcSysInfo::getProcessCpuPercent(const pid_t p)
{
	unsigned int totaltime1, totaltime2;
	unsigned int procetime1,  procetime2;

	totaltime1 = get_cpu_total_occupy();
	if(totaltime1 == 0)
		return 0.0;
	procetime1 = get_cpu_process_occupy(p);
	if(procetime1 == 0)
		return 0.0;

	usleep(500*1000);

	totaltime2 = get_cpu_total_occupy();
	if(totaltime2 == 0)
		return 0.0;
	procetime2 = get_cpu_process_occupy(p);
	if(procetime2 == 0)
		return 0.0;

	//    return 100.0*(procetime2 - procetime1)*1.0/((totaltime2-totaltime1)*1.0);
	return (((procetime2 - procetime1)*10000)/(totaltime2-totaltime1))/100.0;
}

float MxcSysInfo::getProcessCpuPercent(const  char* ProcessName)
{
	pid_t pid = pidof(ProcessName);
	if(pid < 0)
		return 0.0;
	return getProcessCpuPercent(pid);
}




char* MxcSysInfo::get_items(const char *buffer, int ie)
{
	if(buffer == NULL)
		return NULL;

	char *p =const_cast<char*>(buffer);
	int len = strlen(buffer);
	int count = 0;

	if( ie <= 1 )
		return p;

	int i;
	for (i = 0; i<len; i++)
	{
		if(' ' == *p)
		{
			count++;
			if (count == ie - 1)
			{
				p++;
				break;
			}
		}
		p++;
	}

	if(i >= (len-1))
		return NULL;
	else
		return p;
}


pid_t MxcSysInfo::pidof(const char* ProcessName)
{
	DIR *dir;
	struct dirent *d;
	int pid,i = 0;
	char *s;

	int pnlen = strlen(ProcessName);
	dir = opendir("/proc");
	if(!dir)
		return -1;

	while( (d = readdir(dir)) != NULL )
	{
		char exe[PATH_MAX+1];
		char path[PATH_MAX+1];
		int len;
		int namelen;

		if( (pid = atoi(d->d_name)) ==0 )
			continue;

		snprintf(exe, sizeof(exe), "/proc/%s/exe",d->d_name);
		if ((len = readlink(exe,path,PATH_MAX)) < 0)
			continue;

		path[len] = '\0';

		s = strrchr(path, '/');

		if(s == NULL)
			continue;
		s++;

		namelen = strlen(s);

		if(namelen < pnlen)
			continue;

		if(!strncmp(ProcessName, s, pnlen))
		{
			if(s[pnlen] == ' ' || s[pnlen] == '\0')
			{
				closedir(dir);
				return pid;
			}
		}
	}
	closedir(dir);
	return -1;
}

unsigned int MxcSysInfo::getProcessMem(const pid_t p)
{
	return get_phy_mem(p);
}

unsigned int MxcSysInfo::getProcessMem(const char* ProcessName)
{
	pid_t pid = pidof(ProcessName);
	if(pid < 0)
		return 0.0;
	return get_phy_mem(pid);
}

unsigned int MxcSysInfo::getTotalMem()
{
	return get_total_mem();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值