free: code shrink
[oweals/busybox.git] / procps / free.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini free implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under the GPL version 2, see the file LICENSE in this tarball.
8  */
9
10 /* getopt not needed */
11
12 #include "libbb.h"
13
14 int free_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
15 int free_main(int argc UNUSED_PARAM, char **argv)
16 {
17         struct sysinfo info;
18         unsigned mem_unit;
19
20 #if ENABLE_DESKTOP
21         if (argv[1] && argv[1][0] == '-')
22                 bb_show_usage();
23 #endif
24
25         sysinfo(&info);
26
27         /* Kernels prior to 2.4.x will return info.mem_unit==0, so cope... */
28         mem_unit = 1;
29         if (info.mem_unit != 0) {
30                 mem_unit = info.mem_unit;
31         }
32
33         /* Convert values to kbytes */
34         if (mem_unit == 1) {
35                 info.totalram >>= 10;
36                 info.freeram >>= 10;
37 #if BB_MMU
38                 info.totalswap >>= 10;
39                 info.freeswap >>= 10;
40 #endif
41                 info.sharedram >>= 10;
42                 info.bufferram >>= 10;
43         } else {
44                 mem_unit >>= 10;
45                 /* TODO:  Make all this stuff not overflow when mem >= 4 Tb */
46                 info.totalram *= mem_unit;
47                 info.freeram *= mem_unit;
48 #if BB_MMU
49                 info.totalswap *= mem_unit;
50                 info.freeswap *= mem_unit;
51 #endif
52                 info.sharedram *= mem_unit;
53                 info.bufferram *= mem_unit;
54         }
55
56         printf("      %13s%13s%13s%13s%13s\n",
57                 "total",
58                 "used",
59                 "free",
60                 "shared", "buffers" /* swap and total don't have these columns */
61         );
62         printf("%6s%13lu%13lu%13lu%13lu%13lu\n", "Mem:",
63                 info.totalram,
64                 info.totalram - info.freeram,
65                 info.freeram,
66                 info.sharedram, info.bufferram
67         );
68 #if BB_MMU
69         printf("%6s%13lu%13lu%13lu\n", "Swap:",
70                 info.totalswap,
71                 info.totalswap - info.freeswap,
72                 info.freeswap
73         );
74         printf("%6s%13lu%13lu%13lu\n", "Total:",
75                 info.totalram + info.totalswap,
76                 (info.totalram - info.freeram) + (info.totalswap - info.freeswap),
77                 info.freeram + info.freeswap
78         );
79 #endif
80         return EXIT_SUCCESS;
81 }