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

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

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值