Use /proc/meminfo for Memory module

This commit is contained in:
Robinhuett 2018-11-08 21:09:56 +01:00
parent 2d2fb88040
commit ac0963c608
2 changed files with 30 additions and 10 deletions

View File

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

View File

@ -13,13 +13,30 @@ waybar::modules::Memory::Memory(const Json::Value& config)
auto waybar::modules::Memory::update() -> void auto waybar::modules::Memory::update() -> void
{ {
struct sysinfo info = {}; parseMeminfo();
if (sysinfo(&info) == 0) { int used_ram_percentage = 100 * (memtotal_ - memfree_) / memtotal_;
auto total = info.totalram * info.mem_unit;
auto freeram = info.freeram * info.mem_unit;
int used_ram_percentage = 100 * (total - freeram) / total;
label_.set_text(fmt::format(format_, used_ram_percentage)); 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_.set_tooltip_text(fmt::format("{:.{}f}Gb used", used_ram_gigabytes, 1));
} }
void waybar::modules::Memory::parseMeminfo()
{
int memtotal, memfree, memavail, membuffer, memcache;
FILE* info = fopen("/proc/meminfo","r");
if(fscanf (info, "MemTotal: %d kB MemFree: %d kB Buffers: %d kB Cached: %d kB",&memtotal, &memfree, &membuffer, &memcache) < 4) { // Old meminfo format
fclose(info);
info = fopen("/proc/meminfo","r");
if(fscanf(info, "MemTotal: %d kB MemFree: %d kB MemAvailable: %d kB Buffers: %d kB Cached: %d kB",&memtotal, &memfree, &memavail, &membuffer, &memcache) < 5) { // Current meminfo format
memtotal_ = -1;
memfree_ = -1;
} else {
memtotal_ = memtotal;
memfree_ = memavail;
}
} else {
memtotal_ = memtotal;
memfree_ = memfree + (membuffer + memcache);
}
fclose(info);
} }