Skip to content

Instantly share code, notes, and snippets.

@gbmhunter
Last active August 29, 2021 18:47
Show Gist options
  • 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;
}
@kurotych
Copy link

kurotych commented Sep 15, 2018

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:

processMem_t processMem = {0};
....
while(...) {
 ...
if (processMem.physicalMem != 0 && processMem.virtualMem != 0) {
         break;
    }
}

And for what ?
#include "sys/types.h"
#include "sys/sysinfo.h"

@nonetrix
Copy link

nonetrix commented Dec 28, 2020

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;
}

@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