Last active
August 29, 2021 18:47
-
-
Save gbmhunter/00c57b55e2616cd8e1f21f77b79e59fc to your computer and use it in GitHub Desktop.
Code example showing how to get the memory used by the current Linux process in C/C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "sys/types.h" | |
#include "sys/sysinfo.h" | |
int parseLine(char *line) { | |
// This assumes that a digit will be found and the line ends in " Kb". | |
int i = strlen(line); | |
const char *p = line; | |
while (*p < '0' || *p > '9') p++; | |
line[i - 3] = '\0'; | |
i = atoi(p); | |
return i; | |
} | |
typedef struct { | |
uint32_t virtualMem; | |
uint32_t physicalMem; | |
} processMem_t; | |
processMem_t GetProcessMemory() { | |
FILE *file = fopen("/proc/self/status", "r"); | |
char line[128]; | |
processMem_t processMem; | |
while (fgets(line, 128, file) != NULL) { | |
if (strncmp(line, "VmSize:", 7) == 0) { | |
processMem.virtualMem = parseLine(line); | |
break; | |
} | |
if (strncmp(line, "VmRSS:", 6) == 0) { | |
processMem.physicalMem = parseLine(line); | |
break; | |
} | |
} | |
fclose(file); | |
return processMem; | |
} |
code doesn't work at all for me I had to make a lot of changes and it still doesn't compile..
#include <sys/types.h>
#include <sys/sysinfo.h>
#include <cstring>
#include <cstdio>
int parseLine(char *line) {
// This assumes that a digit will be found and the line ends in " Kb".
int i = strlen(line);
const char *p = line;
while (*p < '0' || *p > '9') p++;
line[i - 3] = '\0';
// what is this atoi thing?
i = atoi(p);
return i;
}
typedef struct {
u_int32_t virtualMem;
u_int32_t physicalMem;
} processMem_t;
processMem_t** GetProcessMemory() {
FILE *file = fopen("/proc/self/status", "r");
char line[128];
processMem_t processMem;
while (fgets(line, 128, file) != NULL) {
if (strncmp(line, "VmSize:", 7) == 0) {
processMem.virtualMem = parseLine(line);
break;
}
if (strncmp(line, "VmRSS:", 6) == 0) {
processMem.physicalMem = parseLine(line);
break;
}
}
fclose(file);
return processMem;
}
Is there a way to directly read the raw binary value instead of converting from string?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have bug in this example.
Don't use break while loop in 27, 32 lines . Because you get only VmSize or VmRSS.
You can use break after get two values. Something like that:
And for what ?
#include "sys/types.h"
#include "sys/sysinfo.h"