Obtained through the proc file system
Under proc, there is proc / meminfo. This file will provide the corresponding memory usage at this moment.
Many upper-layer interface data sources of the system are also derived from this.
cat /proc/meminfo
MemTotal: 131921988 kB
MemFree: 90476752 kB
Buffers: 765764 kB
Cached: 13274276 kB
SwapCached: 131872 kB
Active: 27448120 kB
Inactive: 9399016 kB
Active(anon): 21696856 kB
Inactive(anon): 1133872 kB
....
Via sysinfo
In Linux, sysinfo is mainly used to obtain system-related information.
In Linux, sysinfo is a structure used to obtain system-related information.
Function declaration and prototype:
#include <sys/sysinfo.h>
int sysinfo(struct sysinfo *info);
main members.
struct sysinfo {
long uptime;
/* 启动到现在经过的时间 */
unsigned long loads[3];
/* 1, 5, and 15 minute load averages */
unsigned long totalram; /* 总的可用的内存大小 */
unsigned long freeram; /* 还未被使用的内存大小 */
unsigned long sharedram; /* 共享的存储器的大小 */
unsigned long bufferram; /* 缓冲区大小 */
unsigned long totalswap; /* 交换区大小 */
unsigned long freeswap; /* 还可用的交换区大小 */
unsigned short procs; /* 当前进程数目 */
char _f[22]; /* 64字节的补丁结构 */
....
You can use the memory status corresponding to this interface.
Reference example:
size_t getFreeMemorySize()
{
struct sysinfo memInfo;
sysinfo(&memInfo);
return memInfo.freeram/1024/1024;
}