Last active
March 6, 2017 17:42
-
-
Save PolarNick239/ab703902abaea34ba4a1a969143f9ad6 to your computer and use it in GitHub Desktop.
Function to measure available memory on Linux, can be easily adopted to get any value from /proc/meminfo
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 <string.h> | |
#include <cstdlib> | |
bool get_memavailable_from_meminfo(size_t &memavailable) | |
{ | |
const int LINE_LEN = 512; | |
char str[LINE_LEN]; | |
FILE *fp = fopen("/proc/meminfo","rt"); | |
if (fp == NULL) { | |
// perror("Cannot open /proc/meminfo"); | |
return false; | |
} | |
while (true) { | |
if (fgets(str, LINE_LEN, fp) == NULL) { | |
fclose(fp); | |
return false; | |
} | |
if (!strncmp(str, "MemAvailable:", strlen("MemAvailable:"))) { | |
break; | |
} | |
} | |
memavailable = (size_t) atoll(str + strlen("MemAvailable:")) * 1024; // Convert kilobytes to bytes | |
fclose(fp); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment