1 /* vi: set sw=4 ts=4: */
3 * Mini free implementation for busybox
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2, see file LICENSE in this source tree.
10 /* getopt not needed */
12 //usage:#define free_trivial_usage
13 //usage: "" IF_DESKTOP("[-b/k/m/g]")
14 //usage:#define free_full_usage "\n\n"
15 //usage: "Display the amount of free and used system memory"
17 //usage:#define free_example_usage
19 //usage: " total used free shared buffers\n"
20 //usage: " Mem: 257628 248724 8904 59644 93124\n"
21 //usage: " Swap: 128516 8404 120112\n"
22 //usage: "Total: 386144 257128 129016\n"
25 #include "common_bufsiz.h"
27 # include <sys/sysinfo.h>
34 # define G_unit_steps G.unit_steps
36 # define G_unit_steps 10
39 #define G (*(struct globals*)bb_common_bufsiz1)
40 #define INIT_G() do { setup_common_bufsiz(); } while (0)
43 static unsigned long long scale(unsigned long d)
45 return ((unsigned long long)d * G.mem_unit) >> G_unit_steps;
48 static unsigned long parse_cached_kb(void)
50 char buf[60]; /* actual lines we expect are ~30 chars or less */
52 unsigned long cached = 0;
54 fp = xfopen_for_read("/proc/meminfo");
55 while (fgets(buf, sizeof(buf), fp) != NULL) {
56 if (sscanf(buf, "Cached: %lu %*s\n", &cached) == 1)
59 if (ENABLE_FEATURE_CLEAN_UP)
65 int free_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
66 int free_main(int argc UNUSED_PARAM, char **argv IF_NOT_DESKTOP(UNUSED_PARAM))
69 unsigned long long cached;
75 if (argv[1] && argv[1][0] == '-') {
81 /* G.unit_steps = 10; - already is */
83 case 'm': /* 2^(2*10) */
86 case 'g': /* 2^(3*10) */
94 printf(" %11s%11s%11s%11s%11s%11s\n"
99 "shared", "buffers", "cached" /* swap and total don't have these columns */
103 /* Kernels prior to 2.4.x will return info.mem_unit==0, so cope... */
104 G.mem_unit = (info.mem_unit ? info.mem_unit : 1);
105 /* Extract cached from /proc/meminfo and convert to mem_units */
106 cached = ((unsigned long long) parse_cached_kb() * 1024) / G.mem_unit;
108 #define FIELDS_6 "%11llu%11llu%11llu%11llu%11llu%11llu\n"
109 #define FIELDS_3 (FIELDS_6 + 3*6)
110 #define FIELDS_2 (FIELDS_6 + 4*6)
113 scale(info.totalram), //total
114 scale(info.totalram - info.freeram), //used
115 scale(info.freeram), //free
116 scale(info.sharedram), //shared
117 scale(info.bufferram), //buffers
118 scale(cached) //cached
120 /* Show alternate, more meaningful busy/free numbers by counting
121 * buffer cache as free memory. */
122 printf("-/+ buffers/cache:");
123 cached += info.freeram;
124 cached += info.bufferram;
126 scale(info.totalram - cached), //used
132 scale(info.totalswap), //total
133 scale(info.totalswap - info.freeswap), //used
134 scale(info.freeswap) //free