Https://www.cnblogs.com/cxjchen/archive/2013/03/30/2990548.html
The simplest way to view RAM usage is through /proc/meminfo
. This dynamically updated virtual file is actually a combination of many other memory-related tools (such as: Free/ps/top). /proc/meminfo
lists all the memory usage you want to know.
Memory usage information for processes can also be viewed through/PROC/<PID>/STATM and/proc/<pid>/status.
#include <stdio.h>#include<stdlib.h>#include<unistd.h>//header File#include <assert.h>intGet_phy_mem (Constpid_t P) { Charfile[ -] = {0};//file nameFILE*FD;//define file pointer fd Charline_buff[ the] = {0};//read the buffer of a rowsprintf (file,"/proc/%d/status", p);//the 11th line in the file is covered withfprintf (stderr,"Current pid:%d\n", p); FD= fopen (file,"R");//Open file in R Read and assign to Pointer fd//get Vmrss: Actual physical memory consumption inti; Charname[ +];//Store project name intVmrss;//Store memory Peak size for(i=0; i<vmrss_line-1; i++) {fgets (Line_buff,sizeof(Line_buff), FD); }//read to line 15thFgets (Line_buff,sizeof(Line_buff), FD);//read Vmrss This line of data, Vmrss on line 15thSSCANF (Line_buff,"%s%d", name,&Vmrss); fprintf (stderr,"====%s:%d====\n", Name,vmrss); Fclose (FD); //Close File fd returnVmrss;}intGet_rmem (pid_t p) {returnGet_phy_mem (P);}intGet_total_mem () {Char* File ="/proc/meminfo";//file nameFILE*FD;//define file pointer fd Charline_buff[ the] = {0};//read the buffer of a rowFD = fopen (file,"R");//Open file in R Read and assign to Pointer fd//Get Memtotal: Total memory consumption size inti; Charname[ +];//Store project name intMemtotal;//Store memory Peak sizeFgets (Line_buff,sizeof(Line_buff), FD);//read Memtotal This line of data, memtotal on line 1thSSCANF (Line_buff,"%s%d", name,&memtotal); fprintf (stderr,"====%s:%d====\n", Name,memtotal); Fclose (FD); //Close File fd returnmemtotal;}floatGet_pmem (pid_t p) {intPHY =Get_phy_mem (P); intTotal =Get_total_mem (); floatOccupy = (phy*1.0)/(total*1.0); fprintf (stderr,"====process Mem occupy:%.6f\n====", occupy); returnoccupy;}
Programming methods for CPU consumption and memory consumption of compute processes under Linux ZZ