根据/proc/meminfo对空闲内存进行占用
#include <stdio.h> #include <sys/sysinfo.h>
#include <linux/kernel.h> /* 包含sysinfo结构体信息*/
#include <unistd.h> #include <string>
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <assert.h>
#include <stdlib.h>
using namespace std; ///////////////////////////////////////////////////
// Item Names which should be corresponded to the enum below restrictly
const char * ItemCheckName[] =
{
"MemTotal",
"MemFree",
"Buffers",
"Cached"
}; enum ITEMCHECKNAME
{
MEMTOTAL = ,
MEMFREE,
BUFFERS,
CACHED
}; const int INVALID_VALUE = -;
const char* MEM_INFO_FILE_NAME = "/proc/meminfo";
bool isDebugging = false;
////////////////////////////////////////////////////// string trim(const string& str)
{
string::size_type pos = str.find_first_not_of(' ');
if (pos == string::npos)
{
return str;
}
string::size_type pos2 = str.find_last_not_of(' ');
if (pos2 != string::npos)
{
return str.substr(pos, pos2 - pos + );
}
return str.substr(pos);
} int split(const string& str, vector<string>& ret_, string sep = ",")
{
if (str.empty())
{
return ;
} string tmp;
string::size_type pos_begin = str.find_first_not_of(sep);
string::size_type comma_pos = ; while (pos_begin != string::npos)
{
comma_pos = str.find(sep, pos_begin);
if (comma_pos != string::npos)
{
tmp = str.substr(pos_begin, comma_pos - pos_begin);
pos_begin = comma_pos + sep.length();
}
else
{
tmp = str.substr(pos_begin);
pos_begin = comma_pos;
} if (!tmp.empty())
{
ret_.push_back(tmp);
tmp.clear();
}
}
return ;
} bool CheckAllBeenSet(vector<pair<string, int> > itemsToCheck)
{
vector<pair<string, int> >::iterator it = itemsToCheck.begin();
while (it != itemsToCheck.end())
{
if (it->second == INVALID_VALUE)
{
return false;
} it++;
}
return true;
} void PrintItems(vector<pair<string, int> > itemsToCheck)
{
vector<pair<string, int> >::iterator it = itemsToCheck.begin();
while (it != itemsToCheck.end())
{
cout << "KEY = " << it->first << " , VALUE = " << it->second << " KB "<< endl;
it++;
}
} unsigned int CheckFreeMemInKByte(vector<pair<string, int> > itemsToCheck)
{
// 空闲内存计算方式:如果Cached值大于MemTotal值则空闲内存为MemFree值,否则空闲内存为MemFree值+Buffers值+Cached值
int rlt;
if (itemsToCheck[CACHED].second > itemsToCheck[MEMTOTAL].second)
{
rlt = itemsToCheck[MEMFREE].second;
if (isDebugging)
{
cout << "CACHED(" << itemsToCheck[CACHED].second << "KB) > MEMTOTAL(" << itemsToCheck[MEMTOTAL].second << "KB)\n";
cout << "FreeMemInKb is " << rlt << "KB\n";
}
}
else
{
rlt = itemsToCheck[CACHED].second + itemsToCheck[MEMFREE].second + itemsToCheck[BUFFERS].second;
if (isDebugging)
{
cout << "CACHED(" << itemsToCheck[CACHED].second << "KB) <= MEMTOTAL(" << itemsToCheck[MEMTOTAL].second << "KB)\n";
cout << "FreeMemInKb is " << rlt << "KB\n";
}
} return rlt;
} // usage
int main(int argc, char *agrv[])
{
if (argc < || argc > )
{
cout << "Usage :\n memCons fromTotalMem freePercentage [isDebugging]\n";
cout << "For example : \'memCons 0 1\'\n means to take 99% of freeMem, that is to leave only 1% out of free memory\n";
cout << "For example : \'memCons 1 1\'\n means to take 99% of totalMem, that is to leave only 1% out of all the memory\n";
cout << "For example : \'memCons 1 1 1\'\n means in the debugging mode\n";
return -;
}
bool fromTotalMem = atoi(agrv[]) == ? true : false;
int freePercentage = atoi(agrv[]);
isDebugging = (argc == && atoi(agrv[]) == ) ? true : false; if (!(freePercentage > && freePercentage < ))
{
cout << "the second argument of memCons must between 0 and 100";
return -;
} struct sysinfo s_info;
int error; error = sysinfo(&s_info);
printf("the followings are output from \'sysinfo\' call \n\ncode error=%d\n",error);
printf("Uptime = %ds\nLoad: 1 min%d / 5 min %d / 15 min %d\n"
"RAM: total %d / free %d /shared%d\n"
"Memory in buffers = %d\nSwap:total%d/free%d\n"
"Number of processes = %d\n\n\n",
s_info.uptime, s_info.loads[],
s_info.loads[], s_info.loads[],
s_info.totalram, s_info.freeram,
s_info.totalswap, s_info.freeswap,
s_info.procs ); vector< pair<string, int> > itemsToCheck;
std::pair <std::string, int> memTotal(ItemCheckName[MEMTOTAL], INVALID_VALUE);
itemsToCheck.push_back(memTotal);
std::pair <std::string, int> memfreePair(ItemCheckName[MEMFREE], INVALID_VALUE);
itemsToCheck.push_back(memfreePair);
std::pair <std::string, int> buffers(ItemCheckName[BUFFERS], INVALID_VALUE);
itemsToCheck.push_back(buffers);
std::pair <std::string, int> cached(ItemCheckName[CACHED], INVALID_VALUE);
itemsToCheck.push_back(cached); vector<string> splitedWords; ifstream infile(MEM_INFO_FILE_NAME);
if (infile.fail())
{
cerr << "error in open the file";
return false;
} int hitCnt = itemsToCheck.size();
while(hitCnt != )
{
splitedWords.clear();
char temp[];
infile.getline(temp, ); const string tmpString = temp; split(tmpString, splitedWords, ":"); // use the first part to check whether to continue
splitedWords[] = trim(splitedWords[]);
int foundIndex = -;
for (int i = ; i < itemsToCheck.size(); i++)
{
if (itemsToCheck[i].first == splitedWords[])
{
foundIndex = i;
hitCnt--;
break;
}
} if (foundIndex == -)
{
continue;
} // check the number
string numberInString = trim(splitedWords[]);
int firstNotNumberPos = numberInString.find_first_not_of("");
numberInString.substr(, firstNotNumberPos);
int num = atoi(numberInString.c_str()); // insert into container
itemsToCheck[foundIndex].second = num; if (infile.eof())
{
break;
}
}
infile.close(); PrintItems(itemsToCheck); if (CheckAllBeenSet(itemsToCheck) == false)
{
cout << "Error in checking " << MEM_INFO_FILE_NAME << endl;
return -;
} // set used memory according to the requirements
long long memToUse = ;
long long freeMemCount = ; if (isDebugging)
{
cout << "Need memory use in total one ? " << fromTotalMem << endl;
}
if (!fromTotalMem)
{
if (isDebugging)
{
cout << "Need memory use in free one\n";
}
freeMemCount = CheckFreeMemInKByte(itemsToCheck);
}
else
{
if (isDebugging)
{
cout << "Need memory use in total one\n"; cout << "total memory is " << itemsToCheck[MEMTOTAL].second << "KB, that " << itemsToCheck[MEMTOTAL].second * << "B" << endl;
} freeMemCount = itemsToCheck[MEMTOTAL].second;
} cout << "Free Mem Count is " << freeMemCount << "KB" << endl;
memToUse = freeMemCount * ((double) - (double)((double)freePercentage / (double)) );
cout << "MemToUse is " << memToUse << "KB" << endl; char* memConsumer[];
int j = ;
for (; j < ; j++)
{
memConsumer[j] = NULL;
}
try
{
for (j = ; j < ; j++)
{
if (memConsumer[j] == NULL)
{
memConsumer[j] = new char[memToUse];
}
for (int i = ; i < memToUse; i++)
{
memConsumer[j][i] = '';
}
}
}
catch(std::bad_alloc)
{
// swallow the exception and continue
cout << "no more memory can be allocated, already alloced " << j * memToUse << "B";
}
while ()
{
sleep();
} return ;
}
根据/proc/meminfo对空闲内存进行占用的更多相关文章
- /proc/meminfo详解 = /nmon analysis --MEM
memtotal hightotal lowtotal swaptotal memfree highfree lowfree swapfree memshared cached active bigf ...
- linux /proc/meminfo 文件分析(转载)
cat /proc/meminfo 读出的内核信息进行解释,下篇文章会简单对读出该信息的代码进行简单的分析. # cat /proc/meminfo MemTotal: kB MemFr ...
- linux查内存操作:cat /proc/meminfo
https://www.cnblogs.com/zhuiluoyu/p/6154898.html cat /proc/meminfo
- /proc/cpuinfo和/proc/meminfo来查看cpu信息与内存信息
#一般情况下使用root或者oracle用户查都可以. # 总核数 = 物理CPU个数 X 每颗物理CPU的核数 # 总逻辑CPU数 = 物理CPU个数 X 每颗物理CPU的核数 X 超线程数 --查 ...
- [C++]Linux之虚拟文件系统[/proc]中关于CPU/内存/网络/内核等的一些概要性说明
声明:如需引用或者摘抄本博文源码或者其文章的,请在显著处注明,来源于本博文/作者,以示尊重劳动成果,助力开源精神.也欢迎大家一起探讨,交流,以共同进步- 0.0 1.Linux虚拟文件系统 首先要明白 ...
- Prometheus Node_exporter 之 Memory Detail Meminfo /proc/meminfo
1. Memory Active / Inactive type: GraphUnit: bytesLabel: BytesInactive - 最近使用较少的内存, 优先被回收利用 /proc/me ...
- /proc/meminfo
/proc/meminfo 可以查看自己服务器 物理内存 注意这个文件显示的单位是kB而不是KB,1kB=1000B,但是实际上应该是KB,1KB=1024B 这个显示是不精确的,是一个已知的没有被 ...
- /PROC/MEMINFO之谜
网站转自:http://linuxperf.com/?p=142 非常技术的网站,够看上一阵子的(一篇文章) /proc/meminfo是了解Linux系统内存使用状况的主要接口,我们最常用的”fre ...
- /proc/meminfo分析(一)
本文主要分析/proc/meminfo文件的各种输出信息的具体含义. 一.MemTotal MemTotal对应当前系统中可以使用的物理内存. 这个域实际是对应内核中的totalram_pages这个 ...
随机推荐
- 解决:git warning: LF will be replaced by CRLF in xxxx
一. git add -A报错 在利用git add -A添加文件时,意外的发现报错了 报错信息中: LF:Line Feed 换行 CRLF:Carriage Return Line Feed 回 ...
- 51nod 1276
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1276 1276 岛屿的数量 题目来源: Codility 基准时间限制: ...
- gradle_学习_01_gradle安装与基本使用
一.下载安装 1.下载地址 官方下载地址: https://gradle.org/install/#manually 下载二进制文件,解压即可 2.环境变量配置 加入以下环境变量 GRADLE_HOM ...
- AOP注解式拦截
1. 自己定义的拦截注解 package com.spring.aop; import java.lang.annotation.Documented; import java.lang.annota ...
- NYOJ-626-intersection set(二分查找)
题目链接 /* Name:NYOJ-626-intersection set Copyright: Author: Date: 2018/4/12 21:30:10 Description: 二分查找 ...
- _Meta 部分用法
model.UserInfo._meta.app_label #获取该类所在app的app名称 model.UserInfo._meta.model_name #获取该类对应表名(字符串类型) mod ...
- python虚拟开发环境搭建(virtualenv和virtualenvwrapper)
虚拟开发环境的搭建 (0) 搭建虚拟环境的意义 使不同的开发环境独立 环境升级不影响其他开发环境,也不影响全局 防止包管理的混乱 (1) 指定 虚拟环境的创建目录 环境变量设置 创建 WORKON_H ...
- HihoCoder1403 后缀数组一·重复旋律1
后缀数组一·重复旋律 时间限制:5000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi平时的一大兴趣爱好就是演奏钢琴.我们知道一个音乐旋律被表示为长度为 N 的数构成的数列. 小Hi ...
- mapper.xml文件中标签不显示问题
1.配置mybatis-3-mapper.dtd 2.配置mybatis-3-config.dtd 3.结果所示:
- LeetCode 340. Longest Substring with At Most K Distinct Characters
原题链接在这里:https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/ 题目: Give ...