Bug 1867190 - Add prefs for PHC probablities r=glandium
[gecko.git] / xpcom / base / AvailableMemoryWatcherUtils.h
blob2d70fe5fd0719aacb67fd428c00e6444742bbc59
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
13 namespace mozilla {
15 struct MemoryInfo {
16 unsigned long memTotal;
17 unsigned long memAvailable;
19 // Check /proc/meminfo for low memory. Largely C method for reading
20 // /proc/meminfo.
21 MOZ_MAYBE_UNUSED
22 static nsresult ReadMemoryFile(const char* meminfoPath, MemoryInfo& aResult) {
23 FILE* fd;
24 if ((fd = fopen(meminfoPath, "r")) == nullptr) {
25 // Meminfo somehow unreachable
26 return NS_ERROR_FAILURE;
29 char buff[128];
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
39 * and MemAvailable.
41 char namebuffer[20];
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);
50 fclose(fd);
51 return NS_OK;
54 } // namespace mozilla
56 #endif // ifndef mozilla_AvailableMemoryWatcherUtils_h