你如何确定 C++ 中 Linux 系统 RAM 的数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/349889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you determine the amount of Linux system RAM in C++?
提问by Bill the Lizard
I just wrote the following C++ function to programatically determine how much RAM a system has installed. It works, but it seems to me that there should be a simpler way to do this. Can someone tell me if I'm missing something?
我刚刚编写了以下 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;
}
First, I'm using popen("head -n1 /proc/meminfo")
to get the first line of the meminfo file from the system. The output of that command looks like
首先,我使用popen("head -n1 /proc/meminfo")
从系统中获取 meminfo 文件的第一行。该命令的输出看起来像
MemTotal: 775280 kB
内存总量:775280 kB
Once I've got that output in an istringstream
, it's simple to tokenize it to get at the information I want. My question is, is there a simpler way to read in the output of this command? Is there a standard C++ library call to read in the amount of system RAM?
一旦我在 中获得了该输出istringstream
,就很容易对其进行标记以获取我想要的信息。我的问题是,是否有更简单的方法来读取此命令的输出?是否有标准的 C++ 库调用来读取系统 RAM 的数量?
回答by Johannes Schaub - litb
On Linux, you can use the function sysinfo
which sets values in the following struct:
在 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 */
};
If you want to do it solely using functions of C++ (i would stick to sysinfo
), i recommend taking a C++ approach using std::ifstream
and std::string
:
如果您只想使用 C++ 的函数(我会坚持使用sysinfo
)来完成它,我建议使用std::ifstream
和使用 C++ 方法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
}
回答by Adam Rosenfield
There's no need to use popen()
, you can just read the file yourself. Also, if there first line isn't what you're looking for, you'll fail, since head -n1
only reads the first line and then exits. I'm not sure why you're mixing C and C++ I/O like that; it's perfectly OK, but you should probably opt to go all C or all C++. I'd probably do it something like this:
没有必要使用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;
}
回答by Charlie Martin
Remember /proc/meminfo is just a file. Open the file, read the first line, close the file. Voilá!
记住 /proc/meminfo 只是一个文件。打开文件,阅读第一行,关闭文件。瞧!