根据/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这个 ...
随机推荐
- java: Comparable比较器,数组对象比较器
Arrays只适合一个数组/对象内的数值进行比较, Comparable比较器(Compara)适合数组,对象,队列等排序, Comparable是一个接口类,实现此接口必须复写:compareTo ...
- P1216 [IOI1994][USACO1.5]数字三角形 Number Triangles
P1216 [IOI1994][USACO1.5]数字三角形 Number Triangles 这个题吧,之前学DP的时候就做过一次了,其实还是挺简单的,如果一步一步按照找状态定义,找边界条件,找转移 ...
- coco2d-js 节点的属性和动作
记录一些coco简单的属性和动作,位置,锚点,透明度,大小,移动等 /*属性*/ if(!true){ var sprite1 = new cc.Sprite(res.Sp1); var sprite ...
- Tomcat部署项目后有括号的处理方法
常见的问题,收录整理了一下,方便查找. 如下3个地方都修改为一致即可解决. 1,右键项目名 --> properties --> 输入web project settings --> ...
- 简单的shell语句
1,重启tomcat 脚本: pid=`ps -ef|grep tomcat |grep -v grep |awk '{print $2}'` ##取tomcat的进程号,awk处理字符串 ,取一行的 ...
- Python3.6.0安装
1.安装 具体详情请参考下图: 双击安装包: 勾选“add python 3.6 to PATH”这样可以自动生成环境变量,选择“Customize installation”自定义安装. 2. ...
- php程序员应该掌握的技能包
作为一名web开发者来说,不论是php还是java web,就我目前掌握的知识来说,个人认为应该掌握以下几个方面的内容 1 基础的编程语言,这个好像是废话 2 软件设计的思想,如面向对象.mvc.各种 ...
- 剑指offer--19.重建二叉树
先序:根>左>右 中序:左>根>右 后序:左>右>根 e.g. {1,2,4,7,3,5,6,8} {4,7,2,1,5,3,8,6} 先序第一个元素是根节点,在中 ...
- Leetcode 904. Fruit Into Baskets
sliding window(滑动窗口)算法 class Solution(object): def totalFruit(self, tree): """ :type ...
- UVALive 3971 Assemble(二分+贪心)
本题思路不难,但是要快速准确的AC有点儿考验代码功力. 看了大白书上的标程,大有所获. 用map和vector的结合给输入分组,这个数据结构的使用非常精美,恰到好处. #include<iost ...