linux物理内存,虚拟内存的获取

使用文件流的方式,解析   cat /proc/meminfo 文件里面的数据

 

#include <iostream>  
#include <fstream>  
#include <sstream>  
#include <string>  
#include <unordered_map>  
#include <map>

struct BASE_INFO_S{
    unsigned long long MemTotalMb; //总的物理内存
    unsigned long long MemUsedMb;  //已使用的物理内存

    unsigned long long SwapTotalMb;//总的虚拟内存
    unsigned long long SwapUsedMb;//已使用的虚拟内存


};

// cat /proc/meminfo
std::map<std::string, std::string> parseMeminfo() {  
    //std::unordered_map<std::string, std::string> meminfo;  
    std::map<std::string, std::string> meminfo;  
    std::ifstream file("/proc/meminfo");  
    std::string line;  
  
    if (file.is_open()) {  
        while (std::getline(file, line)) {  
            std::istringstream iss(line);  
            std::string key, value;  
            if (!(iss >> key >> value)) continue;  
            meminfo[key] = value;  
        }  
        file.close();  
    } else {  
        std::cerr << "Error: Could not open /proc/meminfo" << std::endl;  
    }  

    std::cout<<"========================================================="<<std::endl;
    for(auto it = meminfo.begin(); it != meminfo.end(); ++it){
        std::cout << it->first << ": " << it->second << std::endl;
    }
    std::cout<<"========================================================="<<std::endl;

    BASE_INFO_S baseInfo={0};
    baseInfo.MemTotalMb = std::stoll(meminfo["MemTotal:"]) / 1;
    baseInfo.MemUsedMb = (std::stoll(meminfo["MemTotal:"]) - std::stoll(meminfo["MemFree:"]) - std::stoll(meminfo["Buffers:"]) - std::stoll(meminfo["Cached:"])) / 1;

    baseInfo.SwapTotalMb = std::stoll(meminfo["SwapTotal:"]) / 1;
    baseInfo.SwapUsedMb = (std::stoll(meminfo["SwapTotal:"]) - std::stoll(meminfo["SwapFree:"])) / 1;

    std::cout<<"MemTotalMb:"<<baseInfo.MemTotalMb<<std::endl;
    std::cout<<"MemUsedMb:"<<baseInfo.MemUsedMb<<std::endl;
    std::cout<<"SwapTotalMb:"<<baseInfo.SwapTotalMb<<std::endl;
    std::cout<<"SwapUsedMb:"<<baseInfo.SwapUsedMb<<std::endl;
    return meminfo;  
}  
  
int main() {  
    auto meminfo = parseMeminfo();  
    return 0;  
}

 

posted @ 2024-03-31 08:37  He_LiangLiang  阅读(14)  评论(0编辑  收藏  举报