Memory usage of current process in C

后端 未结 7 1476
深忆病人
深忆病人 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:10

    I'm late to the party, but this might be helpful for anyone else looking for the resident and virtual (and their peak values so far) memories on linux.

    It's probably pretty terrible, but it gets the job done.

    #include 
    #include 
    #include 
    
    
    /*
     * Measures the current (and peak) resident and virtual memories
     * usage of your linux C process, in kB
     */
    void getMemory(
        int* currRealMem, int* peakRealMem,
        int* currVirtMem, int* peakVirtMem) {
    
        // stores each word in status file
        char buffer[1024] = "";
    
        // linux file contains this-process info
        FILE* file = fopen("/proc/self/status", "r");
    
        // read the entire file
        while (fscanf(file, " %1023s", buffer) == 1) {
    
            if (strcmp(buffer, "VmRSS:") == 0) {
                fscanf(file, " %d", currRealMem);
            }
            if (strcmp(buffer, "VmHWM:") == 0) {
                fscanf(file, " %d", peakRealMem);
            }
            if (strcmp(buffer, "VmSize:") == 0) {
                fscanf(file, " %d", currVirtMem);
            }
            if (strcmp(buffer, "VmPeak:") == 0) {
                fscanf(file, " %d", peakVirtMem);
            }
        }
        fclose(file);
    }
    

提交回复
热议问题