【C/C++】监控系统内存代码

  • Post author:
  • Post category:其他


项目代码用的,为了方便以后回顾,记录一下

#include <stdio.h> 
#include <stdint.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h> 
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#define MRYRATIO 100
#define WARNRATIO 20
unsigned long total_memory=0,available_memory=0;
double available ratio;
static int is_memory_alarm; 
int time_count;

bool GetRamInKB(){
FILE *meminfo =fopen("/proc/meminfo""r") ;
if(meminfo == NULL){
printf("open /proc/meminfo failed!\n"); 
return false;
}
char line[256];
while(fgets(line,sizeof(line),meminfo)){
if(sscanf(line,"MemTotal:%dkB",&total_memory)==1){
printf("get total memory success !\n");
continue;
}
if (sscanf(line "MemAvallable:%dkB" &available_memory) == 1){ 
printf("get available memory success !\n"); 
fclose(meminfo); 
return true,
}
}
fclose(meminfo); 
return false;
}
void CheckSysinfo(){ 
if(!GetRamInKB()){
printf("get system memory failed!\n");
is_memory_alarm = 0; 
return;
}
if (!total_memory){
printf("total memory is O\n"); 
is_memory_alarm=0; 
return;
}
available ratio =MRYRATIO * available memory / total memory;
available_ratio <WARNRATIO ? is_memory_alarm=1:is_memory_alarm =0; 
if(is memory alarm){
printf("system memory not enough , total memory [%ld] , available memory [%ld] , available ratio [%lf]\n",
total_memory,
available_memory available_ratio);
}
printf("system memory info, total memory [%ld] , available memory [%ld] , available ratio[%lf]\n",total_memory,available_memory,available_ratio);

void *task(void *arg){
int i=0:
while(i <999){
CheckSysinfo(); 
time_count++;
 usleep(10000); 
 i++;
 }
 }

int main() {
pthread_tp_task; 
int arg = 10;
int ret =pthread_create(&p_task,nullptr,&task,(void *)arg); 
if (ret != 0){
printf("pthread create failed !"); 
return 0;
}
pthread_join(p_task,NULL); 
usleep(1000000); return 0;
}



版权声明:本文为Frederick_Fung原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。