一、功能介绍
通过sysinfo函数获取系统内存的使用情况。
sysinfo函数的帮助页如下:
wbyq@wbyq:/mnt/hgfs/linux-share-dir/linux_c$ man sysinfo SYSINFO(2) Linux Programmer's Manual SYSINFO(2) NAME sysinfo - return system information SYNOPSIS #include <sys/sysinfo.h> int sysinfo(struct sysinfo *info); DESCRIPTION sysinfo() returns certain statistics on memory and swap usage, as well as the load average. Until Linux 2.3.16, sysinfo() returned information in the following structure: struct sysinfo { long uptime; /* Seconds since boot */ unsigned long loads[3]; /* 1, 5, and 15 minute load averages */ unsigned long totalram; /* Total usable main memory size */ unsigned long freeram; /* Available memory size */ unsigned long sharedram; /* Amount of shared memory */ unsigned long bufferram; /* Memory used by buffers */ unsigned long totalswap; /* Total swap space size */ unsigned long freeswap; /* Swap space still available */ unsigned short procs; /* Number of current processes */ char _f[22]; /* Pads structure to 64 bytes */ }; In the above structure, the sizes of the memory and swap fields are given in bytes.
二、程序源码
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/sysinfo.h> int main(int argc,char **argv) { /*2. 获取当前系统内存使用情况*/ struct sysinfo s_info; char info_buff[100]; while(1) { if(sysinfo(&s_info)==0) { sprintf(info_buff,"总内存: %.ld M",s_info.totalram/1024/1024); printf("%s\n",info_buff); sprintf(info_buff,"未使用内存: %.ld M",s_info.freeram/1024/1024); printf("%s\n",info_buff); sprintf(info_buff,"交换区总内存: %.ld M",s_info.totalswap/1024/1024); printf("%s\n",info_buff); sprintf(info_buff,"交换区未使用内存: %.ld M",s_info.freeswap/1024/1024); printf("%s\n",info_buff); sprintf(info_buff,"系统运行时间: %.ld 分钟",s_info.uptime/60); printf("%s\n",info_buff); printf("\n\n"); } sleep(1); } return 0; }
三、运行效果