Memory usage of current process in C

后端 未结 7 1496
深忆病人
深忆病人 2020-12-01 04:22

I need to get the memory usage of the current process in C. Can someone offer a code sample of how to do this on a Linux platform?

I\'m aware of the cat /proc/

7条回答
  •  旧巷少年郎
    2020-12-01 05:01

    This is a terribly ugly and non-portable way of getting the memory usage, but since getrusage()'s memory tracking is essentially useless on Linux, reading /proc//statm is the only way I know of to get the information on Linux.

    If anyone know of cleaner, or preferably more cross-Unix ways of tracking memory usage, I would be very interested in learning how.

    typedef struct {
        unsigned long size,resident,share,text,lib,data,dt;
    } statm_t;
    
    void read_off_memory_status(statm_t& result)
    {
      unsigned long dummy;
      const char* statm_path = "/proc/self/statm";
    
      FILE *f = fopen(statm_path,"r");
      if(!f){
        perror(statm_path);
        abort();
      }
      if(7 != fscanf(f,"%ld %ld %ld %ld %ld %ld %ld",
        &result.size,&result.resident,&result.share,&result.text,&result.lib,&result.data,&result.dt))
      {
        perror(statm_path);
        abort();
      }
      fclose(f);
    }
    

    From the proc(5) man-page:

       /proc/[pid]/statm
              Provides information about memory usage, measured in pages.  
              The columns are:
    
                  size       total program size
                             (same as VmSize in /proc/[pid]/status)
                  resident   resident set size
                             (same as VmRSS in /proc/[pid]/status)
                  share      shared pages (from shared mappings)
                  text       text (code)
                  lib        library (unused in Linux 2.6)
                  data       data + stack
                  dt         dirty pages (unused in Linux 2.6)
    

提交回复
热议问题