|
| 1 | +/** |
| 2 | + * @file cached_memory.cpp |
| 3 | + * @author Charliechen114514 (chengh1922@mails.jlu.edu.cn) |
| 4 | + * @brief Linux-specific Cached Memory Query Implementation |
| 5 | + * @version 0.1 |
| 6 | + * @date 2026-02-27 |
| 7 | + * |
| 8 | + * @copyright Copyright (c) 2026 |
| 9 | + * |
| 10 | + */ |
| 11 | +#include "cached_memory.h" |
| 12 | + |
| 13 | +#include <cstdio> |
| 14 | +#include <cstdint> |
| 15 | +#include <cstring> |
| 16 | + |
| 17 | +namespace cf { |
| 18 | +namespace linux_impl { |
| 19 | + |
| 20 | +namespace { |
| 21 | + |
| 22 | +bool parseMemInfoLine(const char* line, const char* fieldName, uint64_t& outKb) { |
| 23 | + size_t fieldNameLen = strlen(fieldName); |
| 24 | + if (strncmp(line, fieldName, fieldNameLen) != 0) { |
| 25 | + return false; |
| 26 | + } |
| 27 | + |
| 28 | + const char* p = line + fieldNameLen; |
| 29 | + while (*p == ':' || *p == ' ' || *p == '\t') { |
| 30 | + p++; |
| 31 | + } |
| 32 | + |
| 33 | + if (*p == '\0') { |
| 34 | + return false; |
| 35 | + } |
| 36 | + |
| 37 | + char* end; |
| 38 | + unsigned long value = strtoul(p, &end, 10); |
| 39 | + if (end == p) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + outKb = static_cast<uint64_t>(value); |
| 44 | + return true; |
| 45 | +} |
| 46 | + |
| 47 | +} // anonymous namespace |
| 48 | + |
| 49 | +void queryCachedMemory(CachedMemory& cached) { |
| 50 | + FILE* fp = fopen("/proc/meminfo", "r"); |
| 51 | + if (!fp) { |
| 52 | + cached.buffers_bytes = 0; |
| 53 | + cached.cached_bytes = 0; |
| 54 | + cached.shared_bytes = 0; |
| 55 | + cached.slab_bytes = 0; |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + uint64_t buffers = 0; |
| 60 | + uint64_t cachedMem = 0; |
| 61 | + uint64_t shmem = 0; |
| 62 | + uint64_t slab = 0; |
| 63 | + |
| 64 | + char line[256]; |
| 65 | + while (fgets(line, sizeof(line), fp)) { |
| 66 | + uint64_t value; |
| 67 | + if (parseMemInfoLine(line, "Buffers", value)) { |
| 68 | + buffers = value; |
| 69 | + } else if (parseMemInfoLine(line, "Cached", value)) { |
| 70 | + // Note: There may also be "SReclaimable:" which is similar to Cached |
| 71 | + // For simplicity, we only get the main Cached value |
| 72 | + cachedMem = value; |
| 73 | + } else if (parseMemInfoLine(line, "Shmem", value)) { |
| 74 | + shmem = value; |
| 75 | + } else if (parseMemInfoLine(line, "Slab", value)) { |
| 76 | + slab = value; |
| 77 | + } |
| 78 | + |
| 79 | + if (buffers > 0 && cachedMem > 0 && shmem > 0 && slab > 0) { |
| 80 | + break; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + fclose(fp); |
| 85 | + |
| 86 | + // Convert KB to bytes |
| 87 | + cached.buffers_bytes = buffers * 1024; |
| 88 | + cached.cached_bytes = cachedMem * 1024; |
| 89 | + cached.shared_bytes = shmem * 1024; |
| 90 | + cached.slab_bytes = slab * 1024; |
| 91 | +} |
| 92 | + |
| 93 | +} // namespace linux_impl |
| 94 | +} // namespace cf |
0 commit comments