fix(Swap): fix reading procfs files and simplify data parsing

This commit is contained in:
apocelipes
2023-12-04 17:28:46 +09:00
committed by Carter Li
parent 6eae425679
commit ed879ee53c
+11 -15
View File
@@ -8,25 +8,21 @@
const char* ffDetectSwap(FFSwapResult* swap)
{
// #620
FF_AUTO_CLOSE_FILE FILE* meminfo = fopen("/proc/meminfo", "r");
if (!meminfo) return "fopen(\"/proc/meminfo\", \"r\") failed";
char buf[PROC_FILE_BUFFSIZ];
ssize_t nRead = ffReadFileData("/proc/meminfo", sizeof(buf) - 1, buf);
if(nRead < 0)
return "ffReadFileData(\"/proc/meminfo\", sizeof(buf)-1, buf)";
buf[nRead] = '\0';
uint64_t swapTotal = 0, swapFree = 0;
char* FF_AUTO_FREE line = NULL;
size_t len = 0;
uint8_t count = 0;
char *token = NULL;
if ((token = strstr(buf, "SwapTotal:")) != NULL)
sscanf(token, "SwapTotal: %" PRIu64, &swapTotal);
if ((token = strstr(buf, "SwapFree:")) != NULL)
sscanf(token, "SwapFree: %" PRIu64, &swapFree);
while (getline(&line, &len, meminfo) != EOF)
{
if (line[0] == 'S')
{
if(sscanf(line, "SwapTotal: %" PRIu64, &swapTotal) > 0 || sscanf(line, "SwapFree: %" PRIu64, &swapFree) > 0)
if (++count >= 2) goto done;
}
}
done:
swap->bytesTotal = swapTotal * 1024lu;
swap->bytesUsed = (swapTotal - swapFree) * 1024lu;