代码之家  ›  专栏  ›  技术社区  ›  Bill the Lizard

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

  •  21
  • Bill the Lizard  · 技术社区  · 16 年前

    我刚刚编写了下面的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文件的第一行。该命令的输出看起来像

    内存总量:775280 KB

    一旦我在一个 istringstream 它很容易标记化以获取我想要的信息。我的问题是,有没有更简单的方法来读取这个命令的输出?是否有一个标准的C++库调用以读取系统RAM的数量?

    4 回复  |  直到 16 年前
        1
  •  65
  •   Johannes Schaub - litb    16 年前

    在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++的函数来做它(我会坚持) 系统信息 ),我建议使用C++方法。 std::ifstream std::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 rest of the line
            file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        return 0; // nothing found
    }
    
        2
  •  4
  •   Adam Rosenfield    16 年前

    不需要使用 popen() ,您可以自己读取文件。而且,如果第一行不是你要找的,你会失败的,因为 head -n1 只读取第一行,然后退出。我不知道为什么你会像这样混合C和C++ I/O;它完全可以,但是你应该选择全部C或所有C++。我可能会这样做:

    int GetRamInKB(void)
    {
        FILE *meminfo = fopen("/proc/meminfo", "r");
        if(meminfo == NULL)
            ... // handle error
    
        char line[256];
        while(fgets(line, sizeof(line), meminfo))
        {
            int ram;
            if(sscanf(line, "MemTotal: %d kB", &ram) == 1)
            {
                fclose(meminfo);
                return ram;
            }
        }
    
        // If we got here, then we couldn't find the proper line in the meminfo file:
        // do something appropriate like return an error code, throw an exception, etc.
        fclose(meminfo);
        return -1;
    }
    
        3
  •  3
  •   Charlie Martin    16 年前

    记住/proc/meminfo只是一个文件。打开文件,读取第一行,关闭文件。Voice!

        4
  •  0
  •   Bombe    16 年前

    偶数 top (从 procps 解析 /proc/meminfo here .