#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
#include <pakfire/os.h>
#include <pakfire/string.h>
return pakfire_parse_file("/proc/cpuinfo", pakfire_parse_cpuinfo, cpuinfo);
}
+// CPU Stats
+
+static int pakfire_parse_cpustat(char* line, size_t length, void* data) {
+ struct pakfire_cpustat* cpustat = data;
+ struct cpustat {
+ unsigned long int user;
+ unsigned long int nice;
+ unsigned long int system;
+ unsigned long int idle;
+ unsigned long int iowait;
+ unsigned long int irq;
+ unsigned long int softirq;
+ unsigned long int steal;
+ unsigned long int guest;
+ unsigned long int guest_nice;
+ } stat;
+ int r;
+
+ // Only care about the line of interest
+ if (pakfire_string_startswith(line, "cpu ")) {
+ r = sscanf(line, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
+ &stat.user, &stat.nice, &stat.system, &stat.idle, &stat.iowait,
+ &stat.irq, &stat.softirq, &stat.steal, &stat.guest, &stat.guest_nice);
+ if (r < 10)
+ return -EINVAL;
+
+ // Fetch how many ticks a second
+ long int ticks = sysconf(_SC_CLK_TCK);
+
+ // Convert to relative terms
+ cpustat->user = stat.user / ticks;
+ cpustat->nice = stat.nice / ticks;
+ cpustat->system = stat.system / ticks;
+ cpustat->idle = stat.idle / ticks;
+ cpustat->iowait = stat.iowait / ticks;
+ cpustat->irq = stat.irq / ticks;
+ cpustat->softirq = stat.softirq / ticks;
+ cpustat->steal = stat.steal / ticks;
+ cpustat->guest = stat.guest / ticks;
+ cpustat->guest_nice = stat.guest_nice / ticks;
+ }
+
+ return 0;
+}
+
+int pakfire_cpustat(struct pakfire_cpustat* cpustat) {
+ return pakfire_parse_file("/proc/stat", pakfire_parse_cpustat, cpustat);
+}
+
// Meminfo
static int pakfire_parse_meminfo_value(uint64_t* mem, const char* s) {
return EXIT_FAILURE;
}
+// This test parses /proc/stat
+static int test_cpustat(const struct test* t) {
+ struct pakfire_cpustat cpustat = {};
+
+ ASSERT_SUCCESS(pakfire_cpustat(&cpustat));
+
+ ASSERT(cpustat.user >= 0);
+ ASSERT(cpustat.nice >= 0);
+ ASSERT(cpustat.system >= 0);
+ ASSERT(cpustat.idle >= 0);
+ ASSERT(cpustat.iowait >= 0);
+ ASSERT(cpustat.irq >= 0);
+ ASSERT(cpustat.softirq >= 0);
+ ASSERT(cpustat.steal >= 0);
+ ASSERT(cpustat.guest >= 0);
+ ASSERT(cpustat.guest_nice >= 0);
+
+ return EXIT_SUCCESS;
+
+FAIL:
+ return EXIT_FAILURE;
+}
+
// This test parses /proc/meminfo
static int test_meminfo(const struct test* t) {
struct pakfire_meminfo meminfo = {};
int main(int argc, const char* argv[]) {
testsuite_add_test(test_cpuinfo);
+ testsuite_add_test(test_cpustat);
testsuite_add_test(test_meminfo);
return testsuite_run(argc, argv);