内核中获取内存使用情况
在内核编程的过程中,需要获取主机的内存使用率,多方搜索无果,以此为记!
代码如下:
void update_memory_rate()
{
struct sysinfo mem_info;
unsigned long total;
unsigned long free;
unsigned long used;
uint32_t uint_kb;
si_meminfo(&mem_info); //更新内存使用信息,保存在&mem_info中
uint_kb = mem_info.mem_unit / 1024; // 获取每个unit的大小,由于单位是byte,先换成KB,我换算后是 4KB
total = (unsigned long)mem_info.totalram * uint_kb;
free = (unsigned long)mem_info.freeram * uint_kb;
used = total - free;
pr_info("mem total: %ld KB, mem used: %ld KB, uint_kb: %ldKB\n", total, used, (unsigned long)uint_kb);
}
主要用到了结构体struct sysinfo
和函数 si_meminfo()
,这里有几点坑,用 mem_info.totalram 获取的值单位还不是 KB,需要乘以 mem_info.mem_unit ,但 mem_unit 的单位是 Byte,因此需要先换算成KB,再和 mem_info.totalram 的值相乘,才得到想要的值。
输出结果:
free命令查看:
内核中si_meminfo
函数的声明:
extern void si_meminfo(struct sysinfo * val);
位置:linux/mm.h
结构体sysinfo
的定义:
struct sysinfo {
__kernel_long_t uptime; /* Seconds since boot */
__kernel_ulong_t loads[3]; /* 1, 5, and 15 minute load averages */
__kernel_ulong_t totalram; /* Total usable main memory size */
__kernel_ulong_t freeram; /* Available memory size */
__kernel_ulong_t sharedram; /* Amount of shared memory */
__kernel_ulong_t bufferram; /* Memory used by buffers */
__kernel_ulong_t totalswap; /* Total swap space size */
__kernel_ulong_t freeswap; /* swap space still available */
__u16 procs; /* Number of current processes */
__u16 pad; /* Explicit padding for m68k */
__kernel_ulong_t totalhigh; /* Total high memory size */
__kernel_ulong_t freehigh; /* Available high memory size */
__u32 mem_unit; /* Memory unit size in bytes */
char _f[20-2*sizeof(__kernel_ulong_t)-sizeof(__u32)]; /* Padding: libc5 uses this.. */
};
位置:linux/sysinfo.h