#include <stdio.h> #include <unistd.h> long get_memory_usage() { long page_size = sysconf (_SC_PAGESIZE); long num_pages = sysconf (_SC_PHYS_PAGES); long mem = (num_pages/1024) * (page_size/1024); long long free_pages = sysconf (_SC_AVPHYS_PAGES); long long free_mem = (free_pages/1024) * (page_size/1024); fprintf(stderr,"Memory %lld MB\\%lld MB.\n", mem, free_mem); return (long)(free_mem); }
獲取結果與System Monitor中的不一致,不過內存管夠的狀況下通常在150~200MB之間波動,重啓閾值設在100MB能夠湊合用spa
另外一方法code
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> long get_memory_usage() { FILE*file=fopen("/proc/meminfo","r"); if(file == NULL){ fprintf(stderr,"cannot open /proc/meminfo\n"); return 1024; } char keyword[20]; char valuech[20]; long mem =0; long free_mem =0; fscanf(file,"MemTotal: %s kB\n",keyword); mem=atol(keyword)/1000; fscanf(file,"MemFree: %s kB\n",valuech); fscanf(file,"MemAvailable: %s kB\n",valuech); free_mem=atol(valuech)/1000; fclose(file); fprintf(stderr,"Memory %ld MB\\%ld MB.\n", mem, free_mem); return (long)(free_mem); }
與在GUI中可見的剩餘內存相同,推薦做爲參考方法blog