如何获取Linux系统上的内存信息? [英] How to get memory information on Linux system?

查看:341
本文介绍了如何获取Linux系统上的内存信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Linux系统上从C ++代码获取总内存,已用内存,可用内存?

How to get the total memory, used memory, free memory from C++ code on Linux system?

推荐答案

注释Chris Stratton ,你可以在Linux上查询 / proc / 中的大量系统信息,因此请阅读 proc(5);其中包含要顺序读取的文本伪文件(有点像管道)。这些不是真正的磁盘文件,所以读得很快。您需要在每次测量时打开和关闭它们。

As commented by Chris Stratton, you can -on Linux- query a lot of system information in /proc/ so read proc(5); which contain textual pseudo-files (a bit like pipes) to be read sequentially. These are not real disk files so are read very quickly. You'll need to open and close them at every measurement.

在进程中,您可以查询其虚拟记忆体中的org / wiki / Address_spacerel =nofollow>地址空间使用 / proc / self / maps - 和 / proc / self / smaps ;在该进程外,对于另一个pid 1234进程,使用 / proc / 1234 / maps & / proc / 1234 / smaps ;您可以通过 / proc / meminfo

From inside a process, you can query its address space in virtual memory using /proc/self/maps -and /proc/self/smaps; outside of that process, for another process of pid 1234, use /proc/1234/maps & /proc/1234/smaps; you can get system wide memory information thru /proc/meminfo

获取系统范围的内存信息。因此,请在终端中尝试以下命令: / p>

So try the following commands in a terminal:

cat /proc/meminfo
cat /proc/$$/maps
cat /proc/$$/smaps
cat /proc/self/maps

了解更多。

请注意 malloc 免费 new delete )通常使用系统调用请求空格(从内核) mmap(2),但之前管理的是免费 -d内存来重用它,所以经常不要用 munmap 释放内存回内核。在 C内存管理中阅读wikipage。换句话说, 堆在进程之外是不可访问的(因为一些未使用,但可重用于未来 malloc -s,内存保留 mmap -ed)。另请参见 mallinfo(3) malloc_stats(3)

Be aware that malloc and free (used by new and delete) are often requesting space (from the kernel) using syscalls like mmap(2) but are managing previously free-d memory to reuse it, so often don't release memory back to the kernel with munmap. Read wikipage on C memory management. In other words, the used heap is not accessible outside the process (since some unused, but reusable for future malloc-s, memory remains mmap-ed). See also mallinfo(3) and malloc_stats(3).

由于 Justin Lardinois回答了,请使用 valgrind 检测内存泄漏。

As Justin Lardinois answered, use valgrind to detect memory leaks.

高级Linux编程是一本好书。它有几个相关章节。

Advanced Linux Programming is a good book to read. It has several related chapters.

这篇关于如何获取Linux系统上的内存信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆