fix: cpu.c was not coded correctly; some edge cases and using static-width integers

This commit is contained in:
2025-08-12 10:11:45 +02:00
parent bdccc05440
commit 82a33791de
3 changed files with 31 additions and 21 deletions

View File

@@ -1,39 +1,44 @@
#include "cpu.h"
#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
const char *const cpu_path = "/sys/devices/system/cpu/cpu%i/online";
const char cpu_path[] = "/sys/devices/system/cpu/cpu%i/online";
bool getcpu(uint32_t id) {
// get the file path
char path[64]; // contains the file path (max length is 64 due to the path and a bunch of extra wiggle room)
snprintf(path, 64, cpu_path, id); // writes the path using the id
int cpu_getenabled(uint id) {
const size_t pathlen = sizeof(cpu_path) + (uint)(log10(-1u) + 1);
char path[pathlen];
snprintf(path, pathlen, cpu_path, id);
// if the file doesn't exist; return true
if (access(path, R_OK) != 0)
return true;
return 1;
// read a character from the file, store in state
char state = '\0';
FILE *f = fopen(path, "r");
assert(f);
fread(&state, 1, 1, f);
fclose(f);
// return whether state is truthy
return !!(state - 0x30);
return state != '0';
}
void setcpu(uint32_t id, bool state) {
char path[64];
snprintf(path, 64, cpu_path, id);
int cpu_setenabled(uint id, int state) {
const size_t pathlen = sizeof(cpu_path) + (uint)(log10(-1u) + 1);
char path[pathlen];
snprintf(path, pathlen, cpu_path, id);
char s = 0x30 + (char)state; // convert the state to a character
char s = 0x30 + (state & 1);
if (access(path, W_OK) != 0)
return 1;
// write the state to the file (creates file if it doesn't exist)
FILE *f = fopen(path, "w");
assert(f);
fwrite(&s, 1, 1, f);
fclose(f);
return 0;
}

View File

@@ -1,6 +1,10 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "util/intdef.h"
bool getcpu(uint32_t); // gets the state of core (id)
void setcpu(uint32_t, bool); // sets the state of core (id)
/* gets the current state of a CPU thread,
* returns a boolean value (`1` for enabled, `0` for disabled) */
int cpu_getenabled(uint id);
/* sets the current state of a CPU thread.
* returns `0` upon success, `1` upon failure */
int cpu_setenabled(uint id, int state);

View File

@@ -1,3 +1,4 @@
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/sysinfo.h>
@@ -10,10 +11,10 @@
static inline bool cpu_setter(uint32_t id, bool nstate, uint8_t opts) {
bool cstate = !nstate;
if (!(opts & OPT_SET_ALL))
cstate = getcpu(id);
cstate = cpu_getenabled(id);
if (cstate != nstate) {
setcpu(id, nstate);
cpu_setenabled(id, nstate);
return true;
}
return false;