1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_AvailableMemoryWatcherUtils_h
8 #define mozilla_AvailableMemoryWatcherUtils_h
10 #include "mozilla/Attributes.h"
11 #include "nsISupportsUtils.h" // For nsresult
16 unsigned long memTotal
;
17 unsigned long memAvailable
;
19 // Check /proc/meminfo for low memory. Largely C method for reading
22 static nsresult
ReadMemoryFile(const char* meminfoPath
, MemoryInfo
& aResult
) {
24 if ((fd
= fopen(meminfoPath
, "r")) == nullptr) {
25 // Meminfo somehow unreachable
26 return NS_ERROR_FAILURE
;
31 /* The first few lines of meminfo look something like this:
32 * MemTotal: 65663448 kB
33 * MemFree: 57368112 kB
34 * MemAvailable: 61852700 kB
35 * We mostly care about the available versus the total. We calculate our
36 * memory thresholds using this, and when memory drops below 5% we consider
37 * this to be a memory pressure event. In practice these lines aren't
38 * necessarily in order, but we can simply search for MemTotal
42 while ((fgets(buff
, sizeof(buff
), fd
)) != nullptr) {
43 if (strstr(buff
, "MemTotal:")) {
44 sscanf(buff
, "%s %lu ", namebuffer
, &aResult
.memTotal
);
46 if (strstr(buff
, "MemAvailable:")) {
47 sscanf(buff
, "%s %lu ", namebuffer
, &aResult
.memAvailable
);
54 } // namespace mozilla
56 #endif // ifndef mozilla_AvailableMemoryWatcherUtils_h