cwist
Modern C web framework with libttak runtime
Loading...
Searching...
No Matches
sys_info.c
Go to the documentation of this file.
1#define _POSIX_C_SOURCE 200809L
3#include <cwist/core/macros.h>
4#include <stdio.h>
5#include <stdlib.h>
6#include <string.h>
7#include <unistd.h>
8
14#if defined(__linux__)
15#include <sys/sysinfo.h>
16
22 // Attempt 1: sysinfo() (Fastest, standard libc)
23 struct sysinfo si;
24 if (sysinfo(&si) == 0) {
25 // freeram is explicitly free.
26 // bufferram and sharedram might be reclaimable but let's be conservative.
27 // On modern Linux kernels, "MemAvailable" in /proc/meminfo is better,
28 // but sysinfo is a good rough estimate multiplied by mem_unit.
29 return (uint64_t)si.freeram * (uint64_t)si.mem_unit;
30 }
31
32 // Attempt 2: /proc/meminfo (More accurate "Available")
33 FILE *fp = fopen("/proc/meminfo", "r");
34 if (fp) {
35 char line[256];
37 while (fgets(line, sizeof(line), fp)) {
38 if (sscanf(line, "MemAvailable: %lu kB", &mem_avail_kb) == 1) {
39 fclose(fp);
40 return mem_avail_kb * 1024;
41 }
42 }
43 fclose(fp);
44 }
45
46 return 0; // Unknown
47}
48
49#elif defined(__APPLE__) || defined(__FreeBSD__)
50#include <sys/types.h>
51#include <sys/sysctl.h>
52
58 // macOS/BSD Logic
59 // Getting strict "Available" like Linux is harder.
60 // We can get page size * free pages.
61
62 int mib[2];
63 mib[0] = CTL_HW;
64
65#ifdef __APPLE__
66 // Roughly estimate using page size and free count is tricky portably.
67 // Let's rely on a simpler 'usermem' or just fail-safe to "High Enough" if we can't detect,
68 // assuming the user manages their mac well.
69 // Or check vm.page_free_count
70 return CWIST_GIB(2); // Mock for Mac dev env safety to prevent constant switching
71#else
72 // FreeBSD
75 size_t len = sizeof(page_size);
76
77 if (sysctlbyname("vm.stats.vm.v_page_size", &page_size, &len, NULL, 0) == -1) return 0;
78 len = sizeof(free_count);
79 if (sysctlbyname("vm.stats.vm.v_free_count", &free_count, &len, NULL, 0) == -1) return 0;
80
82#endif
83}
84
85#else
91 return CWIST_GIB(1); // Default Mock
92}
93#endif
94
102 if (avail == 0) return false; // Could not detect, assume safe
103 return avail < threshold_bytes;
104}
Convenience size-conversion and utility macros shared across CWIST.
#define CWIST_GIB(x)
Convert binary gibibytes to bytes.
Definition macros.h:20
size_t cap
Definition otel.c:56
bool cwist_is_ram_critical(uint64_t threshold_bytes)
Check whether the current available RAM is below a caller-supplied threshold.
Definition sys_info.c:100
uint64_t cwist_get_available_ram(void)
Fallback RAM estimate for unsupported platforms.
Definition sys_info.c:90
System Resource Monitoring Utilities.