#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 ;
}

最新文章

  1. 《深入浅出Windows 10通用应用开发》
  2. 苹果开发者账号如何多人协作进行开发和真机调试XCode
  3. CI控制器的继承问题
  4. js基础第3天
  5. 动态代理与AOP
  6. 如何在ASP.NET端获取屏幕宽度
  7. Android AsyncHttpClient
  8. js正则语法
  9. use EXPORT和use EXPORT_OK
  10. 飘逸的python - zlib压缩存到数据库
  11. 分享45个android实例源码,很好很强大.收藏吧!!!
  12. MVC WebAPI自动生成帮助文档(转)
  13. 25.创业真的需要app吗?真的需要外包吗?
  14. BZOJ_4269_再见Xor_线性基
  15. PL2303HX在Windows 10下面不装安装驱动的解决办法(Code:10)
  16. NLP入门(七)中文预处理之繁简体转换及获取拼音
  17. web服务器的原理
  18. Oracle配置SQL空间操作要点说明
  19. python爬虫学习之查询IP地址对应的归属地
  20. 通过Cookie跳过登录验证码【限cookie不失效有用】

热门文章

  1. SQL Server 性能优化之RML Utilities:快速入门(Quick Start)(1)
  2. docker安装 之 ---CentOS 7 系统脚本自动安装
  3. 条款35:考虑virtual函数以外的其他选择
  4. HiHo 1032 最长回文子串 (Manacher算法求解)
  5. Windows vs Linux:\r\n 与 \r
  6. 浅谈FFT(快速傅里叶变换)
  7. Docker registry 与 持续集成
  8. 【LeetCode】003. Longest Substring Without Repeating Characters
  9. 解决mac下sublime中文乱码
  10. Cloudera API访问