Merge pull request #91 from Robinhuett/ram_free_used

Use /proc/meminfo for Memory module
This commit is contained in:
Alex 2018-11-09 22:34:11 +01:00 committed by GitHub
commit a5bca24f9b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 7 deletions

View File

@ -1,7 +1,7 @@
#pragma once
#include <fmt/format.h>
#include <sys/sysinfo.h>
#include <fstream>
#include "util/chrono.hpp"
#include "ALabel.hpp"
@ -12,6 +12,9 @@ class Memory : public ALabel {
Memory(const Json::Value&);
auto update() -> void;
private:
unsigned long memtotal_;
unsigned long memfree_;
void parseMeminfo();
waybar::util::SleeperThread thread_;
};

View File

@ -13,13 +13,57 @@ waybar::modules::Memory::Memory(const Json::Value& config)
auto waybar::modules::Memory::update() -> void
{
struct sysinfo info = {};
if (sysinfo(&info) == 0) {
auto total = info.totalram * info.mem_unit;
auto freeram = info.freeram * info.mem_unit;
int used_ram_percentage = 100 * (total - freeram) / total;
parseMeminfo();
if(memtotal_ > 0 && memfree_ >= 0) {
int used_ram_percentage = 100 * (memtotal_ - memfree_) / memtotal_;
label_.set_text(fmt::format(format_, used_ram_percentage));
auto used_ram_gigabytes = (total - freeram) / std::pow(1024, 3);
auto used_ram_gigabytes = (memtotal_ - memfree_) / std::pow(1024, 2);
label_.set_tooltip_text(fmt::format("{:.{}f}Gb used", used_ram_gigabytes, 1));
label_.show();
} else {
label_.hide();
}
}
void waybar::modules::Memory::parseMeminfo()
{
long memtotal = -1, memfree = -1, membuffer = -1, memcache = -1, memavail = -1;
int count = 0;
std::string line;
std::ifstream info("/proc/meminfo");
if(info.is_open()) {
while(getline(info, line)) {
auto posDelim = line.find(":");
std::string name = line.substr(0, posDelim);
long value = std::stol(line.substr(posDelim + 1));
if(name.compare("MemTotal") == 0) {
memtotal = value;
count++;
} else if(name.compare("MemAvailable") == 0) {
memavail = value;
count++;
} else if(name.compare("MemFree") == 0) {
memfree = value;
count++;
} else if(name.compare("Buffers") == 0) {
membuffer = value;
count++;
} else if(name.compare("Cached") == 0) {
memcache = value;
count++;
}
if (count >= 5 || (count >= 4 && memavail >= -1)) {
info.close();
}
}
} else {
throw std::runtime_error("Can't open /proc/meminfo");
}
memtotal_ = memtotal;
if(memavail >= 0) {
memfree_ = memavail;
} else {
memfree_ = memfree + (membuffer + memcache);
}
}