简体   繁体   中英

How to get memory information on Linux system?

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

Run your program through valgrind . For a program called foo , for example:

valgrind foo

It'll run the program in a harness that keeps track of memory use and print out that information after the program terminates.

If you don't have valgrind installed for some reason, you should be able to find it in your distro's package repository.

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.

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

So try the following commands in a terminal:

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

to understand more what they could give you.

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) .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM