Skip to content

Commit 4c34f99

Browse files
committed
Swap (Linux): use /proc/swaps
Preparing for detailed swap usage
1 parent d7a8c92 commit 4c34f99

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

src/detection/swap/swap_linux.c

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,28 @@ const char* ffDetectSwap(FFSwapResult* swap)
99
{
1010
// Ref: #620
1111
char buf[PROC_FILE_BUFFSIZ];
12-
ssize_t nRead = ffReadFileData("/proc/meminfo", ARRAY_SIZE(buf) - 1, buf);
13-
if(nRead < 0)
14-
return "ffReadFileData(\"/proc/meminfo\", ARRAY_SIZE(buf)-1, buf)";
12+
ssize_t nRead = ffReadFileData("/proc/swaps", ARRAY_SIZE(buf) - 1, buf);
13+
if(nRead <= 0)
14+
return "ffReadFileData(\"/proc/swaps\", ARRAY_SIZE(buf)-1, buf) failed";
1515
buf[nRead] = '\0';
1616

17-
uint64_t swapTotal = 0, swapFree = 0;
17+
// Skip header
18+
char* line = memchr(buf, '\n', (size_t) nRead);
1819

19-
char *token = NULL;
20-
if ((token = strstr(buf, "SwapTotal:")) != NULL)
21-
swapTotal = strtoul(token + strlen("SwapTotal:"), NULL, 10);
20+
while(line && *++line)
21+
{
22+
uint64_t total, used;
23+
if(sscanf(line, "%*[^\t]%" SCNu64 "%" SCNu64, &total, &used) != 2)
24+
return "Invalid /proc/swaps format found";
2225

23-
if ((token = strstr(buf, "SwapFree:")) != NULL)
24-
swapFree = strtoul(token + strlen("SwapFree:"), NULL, 10);
26+
swap->bytesTotal += total;
27+
swap->bytesUsed += used;
2528

26-
swap->bytesTotal = swapTotal * 1024lu;
27-
swap->bytesUsed = (swapTotal - swapFree) * 1024lu;
29+
line = memchr(line, '\n', (size_t) (nRead - (line - buf)));
30+
}
31+
32+
swap->bytesTotal *= 1024u;
33+
swap->bytesUsed *= 1024u;
2834

2935
return NULL;
3036
}

0 commit comments

Comments
 (0)