如何确定 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 文件的第一行。 该命令的输出看起来像
内存总计:775280 kB
一旦我在 istringstream
中获得该输出,就可以轻松对其进行标记以获取我想要的信息。 有没有更简单的方法来读取此命令的输出? 是否有标准 C++ 库调用来读取系统 RAM 量?
I just wrote the following C++ function to programmatically 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. Am I missing something?
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
MemTotal: 775280 kB
Once I've got that output in an istringstream
, it's simple to tokenize it to get at the information I want. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Linux 上,您可以使用函数
sysinfo
在以下结构中设置值:如果您想仅使用 C++ 函数来完成此操作(我会坚持使用
sysinfo
),我建议采用使用std::ifstream
和std::string
的 C++ 方法:On Linux, you can use the function
sysinfo
which sets values in the following struct:If you want to do it solely using functions of C++ (I would stick to
sysinfo
), I recommend taking a C++ approach usingstd::ifstream
andstd::string
:没有必要使用
popen()
。 您可以自己阅读该文件。另外,如果它们的第一行不是您要查找的内容,您将会失败,因为
head -n1
仅读取第一行,然后退出。 我不知道为什么你要这样混合 C 和 C++ I/O; 完全没问题,但您可能应该选择全部使用 C 或全部使用 C++。 我可能会这样做:There isn't any need to use
popen()
. You can just read the file yourself.Also, if their 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:请记住 /proc/meminfo 只是一个文件。 打开文件,读取第一行,然后关闭文件。 瞧!
Remember /proc/meminfo is just a file. Open the file, read the first line, and close the file. Voilà!
甚至
top
(来自procps
)也会解析/proc/meminfo
。 请参阅此处。Even
top
(fromprocps
) parses/proc/meminfo
. See here.