#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. 只有*.mdf 如何附加数据库到MSSQL

        下载的webform 项目,App_Data文件夹中 只有*.mdf,无*.ldf日志文件. 直接在MSSQL企业管理中 附加数据库  提示附加失败. 新建一个与要附加的数据库同名的数据库,然 ...

  2. Gridview中Datakeys 通过主键取得各列的值。

    首先在初始化Gridview时候定义主键的数组. GridViewTeacherStudent.DataKeyNames=new string[] {"courseId",&quo ...

  3. WebAPI Post请求多参数处理方案

    contentType:"application/json"You need to use JSON.stringify method to convert it to JSON ...

  4. github-如何设置SSH Key

    设置SSH Key 在注册好github账号后,打开你的电脑桌面上的一个文件夹,这就建立了一个本地工作库,在里面点击鼠标右键,找到你的git bash here-点击开,如图所示:进行下面操作: 输入 ...

  5. linux 部署nginx----端口转发

    一.解压安装 tar zxvf nginx-.tar.gz cd nginx- ./configure --with-http_stub_status_module --with-http_ssl_m ...

  6. Python安装升级步骤

    1)安装Pyhton2.7wget http://www.python.org/ftp/python/2.7.5/Python-2.7.5.tar.bz2tar xjvf Python-2.7.5.t ...

  7. XMLSchema验证

    一.什么是Schema(XSD) XML Schema是微软定义的一套用来验证XML技术.是一套预先规定的XML元素和属性创建的,这些元素和属性定义了XML文档的结构和内容模式. DTD的局限性: 1 ...

  8. hdu-3790-最短路径问题(Dijkstra)

    题目链接 /* Name:hdu-3790-最短路径问题 Copyright: Author: Date: 2018/4/16 19:16:25 Description: dijkstra 模板题 * ...

  9. XML的语法

    XML的语法 文档声明: 写法 <?xml version="1.0" ?> 文档声明必须出现在xml文件的第一行和第一列的位置 属性: version="1 ...

  10. 学习动态性能表(11)v$latch$v$latch_children

    学习动态性能表 第十一篇-(1)-V$LATCH  2007.6.7 Oracle Rdbms应用了各种不同类型的锁定机制,latch即是其中的一种.Latch是用于保护SGA区中共享数据结构的一种串 ...