master xplshn/aruu / cmd / pseudo / free.c
 1/* See LICENSE file for copyright and license details. */
 2
 3#include <stdio.h>
 4#include <stdlib.h>
 5
 6#include "util.h"
 7
 8int get_meminfo(struct MemInfo *);
 9
10static unsigned int mem_unit = 1;
11static unsigned int unit_shift;
12
13static unsigned long long
14scale(unsigned long long v)
15{
16  return (v * mem_unit) >> unit_shift;
17}
18
19static void
20usage(void)
21{
22  eprintf("usage: %s [-bkmg]\n", argv0);
23}
24
25// ?man free: display memory usage
26// ?man display the amount of free and used memory in the system
27int
28main(int argc, char *argv[])
29{
30  struct MemInfo mi;
31
32  ARGBEGIN
33  {
34    // ?man -b: specify block size or base directory
35    case 'b':
36      unit_shift = 0;
37      break;
38    // ?man -k: specify option flag
39    case 'k':
40      unit_shift = 10;
41      break;
42    // ?man -m: specify mode or limit
43    case 'm':
44      unit_shift = 20;
45      break;
46    // ?man -g: specify option flag
47    case 'g':
48      unit_shift = 30;
49      break;
50    default:
51      usage();
52  }
53  ARGEND;
54
55  if (argc)
56    usage();
57
58  if (get_meminfo(&mi) < 0)
59    eprintf("get_meminfo:");
60
61  printf("     %13s%13s%13s%13s%13s\n", "total", "used", "free", "shared", "buffers");
62  printf("Mem: ");
63  printf(
64      "%13llu%13llu%13llu%13llu%13llu\n",
65      scale(mi.total),
66      scale(mi.total - mi.free),
67      scale(mi.free),
68      scale(mi.shared),
69      scale(mi.buffers)
70  );
71  printf("-/+ buffers/cache:");
72  printf("%13llu%13llu\n", scale(mi.total - mi.free - mi.buffers), scale(mi.free + mi.buffers));
73  printf("Swap:");
74  printf(
75      "%13llu%13llu%13llu\n",
76      scale(mi.totalswap),
77      scale(mi.totalswap - mi.freeswap),
78      scale(mi.freeswap)
79  );
80
81  if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"))
82    return 1;
83
84  return 0;
85}