#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 = 0,MEMFREE,BUFFERS,CACHED
};const int INVALID_VALUE = -1;
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 + 1);}return str.substr(pos);
}int split(const string& str, vector<string>& ret_, string sep = ",")
{if (str.empty()){return 0;}string tmp;string::size_type pos_begin = str.find_first_not_of(sep);string::size_type comma_pos = 0;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 0;
}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 < 3 || argc > 4){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 -1;}bool fromTotalMem = atoi(agrv[1]) == 1 ? true : false;int freePercentage = atoi(agrv[2]);isDebugging = (argc == 4 && atoi(agrv[3]) == 1) ? true : false;if (!(freePercentage > 0 && freePercentage < 100)){cout << "the second argument of memCons must between 0 and 100";return -1;}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[0],s_info.loads[1], s_info.loads[2],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 != 0){splitedWords.clear();char temp[100];infile.getline(temp, 100); const string tmpString = temp;split(tmpString, splitedWords, ":"); // use the first part to check whether to continuesplitedWords[0] = trim(splitedWords[0]);int foundIndex = -1;for (int i = 0; i < itemsToCheck.size(); i++){if (itemsToCheck[i].first == splitedWords[0]){foundIndex = i;hitCnt--;break;}}if (foundIndex  == -1){continue;}// check the numberstring numberInString = trim(splitedWords[1]);int firstNotNumberPos = numberInString.find_first_not_of("123456789");numberInString.substr(0, firstNotNumberPos);int num = atoi(numberInString.c_str());// insert into containeritemsToCheck[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 -1;}// set used memory according to the requirementslong long memToUse = 0;long long freeMemCount = 0;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 * 1024 << "B" << endl;}freeMemCount = itemsToCheck[MEMTOTAL].second;}cout << "Free Mem Count is " << freeMemCount << "KB" << endl;memToUse = freeMemCount * ((double)1 - (double)((double)freePercentage / (double)100) );cout << "MemToUse  is " << memToUse << "KB" << endl;char* memConsumer[1024];int j = 0;for (; j < 1024; j++){memConsumer[j] = NULL;}try{for (j = 0; j < 1024; j++){if (memConsumer[j] == NULL){memConsumer[j] = new char[memToUse];}for (int i = 0; i < memToUse; i++){memConsumer[j][i] = '5';}}}catch(std::bad_alloc){// swallow the exception and continuecout << "no more memory can be allocated, already alloced " << j * memToUse << "B";}while (1){        sleep(2);}return 0;
}

转载于:https://www.cnblogs.com/aicro/p/3205540.html

根据/proc/meminfo对空闲内存进行占用相关推荐

  1. android meminfo,Android中dumpsys meminfo与/proc/meminfo获取空闲内存不一致的问题

    一.需求 获取当前系统中应用可用的空闲内存. 二.遇到的问题 方法一:dumpsys meminfo Total RAM: 3,498,412K (status normal) Free RAM: 1 ...

  2. 使用/proc/meminfo文件查看内存状态信息

    在Linux下可以使用/proc/meminfo文件查看操作系统内存的使用状态 # cat /proc/meminfo MemTotal: 16333852 kB MemFree: 1633564 k ...

  3. linux kernel内存管理之/proc/meminfo下参数介绍

    一.前言 /proc/meminfo是了解Linux系统内存状态的主要接口,里面统计了当前系统各类内存的使用状况,需要注意的是:这是从内核的角度来统计.我们常用的free,vmstat等指令都是通过/ ...

  4. linux内存实际占用分析

    作者: 黄永兵/译 出处:51CTO.com 阅读提示:本文是为那些经常疑惑的人准备的,"为什么一个简单的KDE文本编辑器要占用25M内存?"导致大多数人认为许多Linux应用程序 ...

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

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

  6. Linux查看CPU和内存使用情况(ps、free、htop、atop、nmon、/proc/meminfo等)

    文章目录 Linux查看CPU和内存使用情况 Linux查看CPU和内存命令:ps 查看系统内存命令:free free与available的区别 htop (推荐) 安装 htop 参数 常用 界面 ...

  7. 【Linux 内核 内存管理】Linux 内核内存布局 ② ( x86_64 架构体系内存分布 | 查看 /proc/meminfo 文件 | /proc/meminfo 重要字段解析 )

    文章目录 一.查看 x86_64 架构体系内存分布 二./proc/meminfo 重要字段解析 一.查看 x86_64 架构体系内存分布 执行 cat /proc/meminfo 命令 , 可以查看 ...

  8. Top 命令 如何查看linux系统中空闲内存/物理内存使用/剩余内存

    1.top命令 top前5行统计信息 ** 第一行: top - 13:59:30 up 15 days, 4:53, 2 users, load average: 1.31, 1.62, 1.41 ...

  9. /proc/meminfo 学习

    在查看linux内存使用情况时,通常需要用到命令(cat /proc/meminfo)查看内核数据结构,有些字段大致知道什么意思,时间久了也容易忘记,故在这里详细记录一下. [root@localho ...

最新文章

  1. formRef=React.createRef() this.formRef.current为null
  2. 数据库内核月报 - 2015 / 11-PgSQL · 答疑解惑 · PostgreSQL 用户组权限管理
  3. 使用服务器测量网站性能,使用服务器时序测量网站性能
  4. 4块硬盘做raid几_Linux高级文件系统管理之RAID
  5. [C++] this指针
  6. MongoDB 之 幽灵操作避免
  7. Maven发布工程到私服
  8. Maven不会吮吸。 。 。 但是Maven文件会
  9. php header什么意思,php header是什么意思
  10. matlab 中sumg,MATLAB)课后实验答案[1]
  11. 【转载】如何扎实的学好ABAP?我的个人经验
  12. python读取matlab数据_两分钟搞定Python读取matlab的.mat数据
  13. Element NavMenu
  14. java调试 Linux_Linux上调试java项目
  15. git 公钥提交代码_Git自由之章 - 关于SSH 公钥
  16. LabVIEW强制重新安装无法运行或损坏的NI软件
  17. CocosCreator如何制作微信小游戏
  18. 千年db服务器注册,千年服务器架设说明.doc
  19. python爬虫入门技术手册
  20. 6D 位姿估计 位姿测量 常用方法总结 (适用于单目标场景)

热门文章

  1. ios html gif 显示,显示gif时出现巨大的内存使用Swift iOS
  2. 我的世界服务器防挂系统,[管理|机制]AFKKicker —— 防挂机!定时要求输入验证码 防止挂机[1.7.10-1.12.2]...
  3. C语言字符串倒排,C语言兑现简单的倒排文件索引
  4. win10 4k分屏 eclipse等工具打开后按钮图标大小问题解决方案
  5. html htc控件详解,*.HTC 文件的简单介绍-网页设计,HTML/CSS
  6. 按网络中计算机所处的,按照网络中计算机所处的地位划分,计算机网络包括
  7. IOS UIScrollView 滚动视图的使用和文档
  8. 第一个脚本-HelloWorld
  9. Python实例 63,64
  10. 简单技能之程序调试入门