Skip to content

Instantly share code, notes, and snippets.

@gbmhunter
Last active August 29, 2021 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbmhunter/00c57b55e2616cd8e1f21f77b79e59fc to your computer and use it in GitHub Desktop.
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++.
#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;
}
@terrancewong
Copy link

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