linux c++获取进程对应的cpu占用率和内存占用情况

转载来源:https://blog.csdn.net/thedarkfairytale/article/details/71079218

背景说明:刚好有个项目上因为不合理的内存占用导致整个系统SSH不能登录,所有需要个监控工具定时记录相关信息。

编译命令:gcc -std=c++11 main.cpp

启动命令:./a.out 进程名字

输出结果:

pid=3259
pcpu=1.234568
procmem=1050176
virtualmem=3259

#include 
#include 
#include 
#include 
#include 
 
#define VMRSS_LINE 17
#define VMSIZE_LINE 13
#define PROCESS_ITEM 14
 
typedef struct {
	unsigned long user;
	unsigned long nice;
	unsigned long system;
	unsigned long idle;
}Total_Cpu_Occupy_t;
 
 
typedef struct {
	unsigned int pid;
	unsigned long utime;  //user time
	unsigned long stime;  //kernel time
	unsigned long cutime; //all user time
        unsigned long cstime; //all dead time
}Proc_Cpu_Occupy_t;
 
 
//获取第N项开始的指针
const char* get_items(const char*buffer ,unsigned int item){
	
	const char *p =buffer;
 
	int len = strlen(buffer);
	int count = 0;
	
	for (int i=0; i [user]\n");
		return 1;
	}
	
	unsigned int pid=0;
	
	if(argc > 2){
		pid = get_pid(argv[1],argv[2]);
	}
	else{
		pid = get_pid(argv[1]);
	}
	
	printf("pid=%d\n",pid);
	printf("pcpu=%f\n",get_proc_cpu(pid));
	printf("procmem=%d\n",get_proc_mem(pid));
	printf("virtualmem=%d\n",get_proc_virtualmem(pid));	
	return 0;
}

 

你可能感兴趣的:(通用编程)