Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

terrancewong commented Aug 29, 2021

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