c++ - 在 C++ 中如何确定 Linux 系统 RAM 的数量?

标签 c++ linux ram

我刚刚编写了以下 C++ 函数,以编程方式确定系统安装了多少 RAM。它有效,但在我看来应该有一种更简单的方法来做到这一点。我错过了什么吗?

getRAM()
{
    FILE* stream = popen("head -n1 /proc/meminfo", "r");
    std::ostringstream output;
    int bufsize = 128;

    while( !feof(stream) && !ferror(stream))
    {
        char buf[bufsize];
        int bytesRead = fread(buf, 1, bufsize, stream);
        output.write(buf, bytesRead);
    }
    std::string result = output.str();

    std::string label, ram;
    std::istringstream iss(result);
    iss >> label;
    iss >> ram;

    return ram;
}

首先,我使用 popen("head -n1/proc/meminfo") 从系统中获取 meminfo 文件的第一行。该命令的输出看起来像

MemTotal: 775280 kB

一旦我在 istringstream 中获得该输出,就可以简单地对其进行标记化以获取我想要的信息。有没有更简单的方法来读取此命令的输出?是否有标准 C++ 库调用来读取系统 RAM 的数量?

最佳答案

在 Linux 上,您可以使用函数 sysinfo 在以下结构中设置值:

   #include <sys/sysinfo.h>

   int sysinfo(struct sysinfo *info);

   struct sysinfo {
       long uptime;             /* Seconds since boot */
       unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
       unsigned long totalram;  /* Total usable main memory size */
       unsigned long freeram;   /* Available memory size */
       unsigned long sharedram; /* Amount of shared memory */
       unsigned long bufferram; /* Memory used by buffers */
       unsigned long totalswap; /* Total swap space size */
       unsigned long freeswap;  /* swap space still available */
       unsigned short procs;    /* Number of current processes */
       unsigned long totalhigh; /* Total high memory size */
       unsigned long freehigh;  /* Available high memory size */
       unsigned int mem_unit;   /* Memory unit size in bytes */
       char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
   };

如果您只想使用 C++ 函数(我会坚持使用 sysinfo),我建议采用 C++ 方法,使用 std::ifstreamstd::string:

unsigned long get_mem_total() {
    std::string token;
    std::ifstream file("/proc/meminfo");
    while(file >> token) {
        if(token == "MemTotal:") {
            unsigned long mem;
            if(file >> mem) {
                return mem;
            } else {
                return 0;
            }
        }
        // Ignore the rest of the line
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return 0; // Nothing found
}

关于c++ - 在 C++ 中如何确定 Linux 系统 RAM 的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652486/

相关文章:

linux - mv 包含来自 shell 脚本的空格的文件

c - 处理器如何读取内存?

tree - SSD时代的编程

c# 将图片文件保存到ram

c++ - 声音多线程

c++ - 在处理 winapi 时,python ctypes 是否与 c++ 不同?

linux - 如何将所有 Unix 用户执行的所有命令记录在一个文件中?

ruby-on-rails - 在 CentOS 7 上安装 Jekyll 错误

c++ - const有什么问题?

C++回调函数运行时错误