#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对空闲内存进行占用的更多相关文章

  1. /proc/meminfo详解 = /nmon analysis --MEM

    memtotal hightotal lowtotal swaptotal memfree highfree lowfree swapfree memshared cached active bigf ...

  2. linux /proc/meminfo 文件分析(转载)

    cat /proc/meminfo    读出的内核信息进行解释,下篇文章会简单对读出该信息的代码进行简单的分析. # cat /proc/meminfo MemTotal:     kB MemFr ...

  3. linux查内存操作:cat /proc/meminfo

    https://www.cnblogs.com/zhuiluoyu/p/6154898.html cat /proc/meminfo

  4. /proc/cpuinfo和/proc/meminfo来查看cpu信息与内存信息

    #一般情况下使用root或者oracle用户查都可以. # 总核数 = 物理CPU个数 X 每颗物理CPU的核数 # 总逻辑CPU数 = 物理CPU个数 X 每颗物理CPU的核数 X 超线程数 --查 ...

  5. [C++]Linux之虚拟文件系统[/proc]中关于CPU/内存/网络/内核等的一些概要性说明

    声明:如需引用或者摘抄本博文源码或者其文章的,请在显著处注明,来源于本博文/作者,以示尊重劳动成果,助力开源精神.也欢迎大家一起探讨,交流,以共同进步- 0.0 1.Linux虚拟文件系统 首先要明白 ...

  6. Prometheus Node_exporter 之 Memory Detail Meminfo /proc/meminfo

    1. Memory Active / Inactive type: GraphUnit: bytesLabel: BytesInactive - 最近使用较少的内存, 优先被回收利用 /proc/me ...

  7. /proc/meminfo

    /proc/meminfo  可以查看自己服务器 物理内存 注意这个文件显示的单位是kB而不是KB,1kB=1000B,但是实际上应该是KB,1KB=1024B 这个显示是不精确的,是一个已知的没有被 ...

  8. /PROC/MEMINFO之谜

    网站转自:http://linuxperf.com/?p=142 非常技术的网站,够看上一阵子的(一篇文章) /proc/meminfo是了解Linux系统内存使用状况的主要接口,我们最常用的”fre ...

  9. /proc/meminfo分析(一)

    本文主要分析/proc/meminfo文件的各种输出信息的具体含义. 一.MemTotal MemTotal对应当前系统中可以使用的物理内存. 这个域实际是对应内核中的totalram_pages这个 ...

随机推荐

  1. Memcache简介 & 内存分配机制

            关于这个东西里面到底应该存放数据网上一直有很多种说法,有的说sql进行md5之后作为键值,结果作为内容存放,也有人说按照业务逻辑错放,反正是炒的不亦乐乎.        本人经过将近2 ...

  2. linux 部署python

    tar xf Python-.tar.xz cd Python-./configure make make install ln -s /usr/local/bin/python2. /usr/bin ...

  3. python sort() sorted() 与argsort()函数的区别

    1.python的内建排序函数有 sort.sorted两个 sort函数只定义在list中,sorted函数对于所有的可迭代序列都可以定义. for example: ls = list([5, 2 ...

  4. SQL1221N The Application Support Layer heap cannot be allocated. SQLSTATE=57011

    不能分配“应用程序支持层“堆 内存不足(系统中可用的调页空间量或交换空间量或系统中可用的物理内存量),可能会导致问题,并提示如下错误信息: SQL1221N  The Application Supp ...

  5. Java_脚本引擎_00_资源帖

    一.精选资料 1.w3cschool—Java 脚本引擎 2.Riding the Nashorn 二.参考资料

  6. 配合Jenkins自动化构建,bat脚本(二)

    批量通过模板,拷贝文件,然后替换模板文件中的标记位为预制的内容. 1 Set servicePath=Ehong.MedicareReview.Web\地区配置\ Set webPath=Ehong. ...

  7. php 中改变字符编码的函数 是 iconv()

    json_enocode()  此函数里边接收的数据必须是utf8格式.要不然会输出null

  8. LeetCode Minimum Absolute Difference in BST

    原题链接在这里:https://leetcode.com/problems/minimum-absolute-difference-in-bst/#/description 题目: Given a b ...

  9. Yii的常用URL和渲染方法

    当前页面url  Yii::app()->request->url;跳转前一个页面url $this->redirect(Yii::app()->request->url ...

  10. bzoj 2142 礼物——扩展lucas模板

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2142 没给P的范围,但说 pi ^ ci<=1e5,一看就是扩展lucas. 学习材料 ...