10f66f451Sopenharmony_ci/* free.c - Display amount of free and used memory in the system.
20f66f451Sopenharmony_ci *
30f66f451Sopenharmony_ci * Copyright 2012 Elie De Brauwer <eliedebrauwer@gmail.com>
40f66f451Sopenharmony_ci
50f66f451Sopenharmony_ci// Flag order is signifcant: b-t are units in order, FLAG_h-1 is unit mask
60f66f451Sopenharmony_ciUSE_FREE(NEWTOY(free, "htgmkb[!htgmkb]", TOYFLAG_USR|TOYFLAG_BIN))
70f66f451Sopenharmony_ci
80f66f451Sopenharmony_ciconfig FREE
90f66f451Sopenharmony_ci  bool "free"
100f66f451Sopenharmony_ci  default y
110f66f451Sopenharmony_ci  help
120f66f451Sopenharmony_ci    usage: free [-bkmgt]
130f66f451Sopenharmony_ci
140f66f451Sopenharmony_ci    Display the total, free and used amount of physical memory and swap space.
150f66f451Sopenharmony_ci
160f66f451Sopenharmony_ci    -bkmgt	Output units (default is bytes)
170f66f451Sopenharmony_ci    -h	Human readable (K=1024)
180f66f451Sopenharmony_ci*/
190f66f451Sopenharmony_ci
200f66f451Sopenharmony_ci#define FOR_free
210f66f451Sopenharmony_ci#include "toys.h"
220f66f451Sopenharmony_ci
230f66f451Sopenharmony_ciGLOBALS(
240f66f451Sopenharmony_ci  unsigned bits;
250f66f451Sopenharmony_ci  unsigned long long units;
260f66f451Sopenharmony_ci  char *buf;
270f66f451Sopenharmony_ci)
280f66f451Sopenharmony_ci
290f66f451Sopenharmony_cistatic char *convert(unsigned long d)
300f66f451Sopenharmony_ci{
310f66f451Sopenharmony_ci  long long ll = d*TT.units;
320f66f451Sopenharmony_ci  char *s = TT.buf;
330f66f451Sopenharmony_ci
340f66f451Sopenharmony_ci  if (FLAG(h)) human_readable(s, ll, 0);
350f66f451Sopenharmony_ci  else sprintf(s, "%llu",ll>>TT.bits);
360f66f451Sopenharmony_ci  TT.buf += strlen(TT.buf)+1;
370f66f451Sopenharmony_ci
380f66f451Sopenharmony_ci  return s;
390f66f451Sopenharmony_ci}
400f66f451Sopenharmony_ci
410f66f451Sopenharmony_civoid free_main(void)
420f66f451Sopenharmony_ci{
430f66f451Sopenharmony_ci  struct sysinfo in;
440f66f451Sopenharmony_ci
450f66f451Sopenharmony_ci  sysinfo(&in);
460f66f451Sopenharmony_ci  TT.units = in.mem_unit ? in.mem_unit : 1;
470f66f451Sopenharmony_ci  while ((toys.optflags&(FLAG_h-1)) && !(toys.optflags&(1<<TT.bits))) TT.bits++;
480f66f451Sopenharmony_ci  TT.bits *= 10;
490f66f451Sopenharmony_ci  TT.buf = toybuf;
500f66f451Sopenharmony_ci
510f66f451Sopenharmony_ci  xprintf("\t\ttotal        used        free      shared     buffers\n"
520f66f451Sopenharmony_ci    "Mem:%17s%12s%12s%12s%12s\n-/+ buffers/cache:%15s%12s\n"
530f66f451Sopenharmony_ci    "Swap:%16s%12s%12s\n", convert(in.totalram),
540f66f451Sopenharmony_ci    convert(in.totalram-in.freeram), convert(in.freeram), convert(in.sharedram),
550f66f451Sopenharmony_ci    convert(in.bufferram), convert(in.totalram - in.freeram - in.bufferram),
560f66f451Sopenharmony_ci    convert(in.freeram + in.bufferram), convert(in.totalswap),
570f66f451Sopenharmony_ci    convert(in.totalswap - in.freeswap), convert(in.freeswap));
580f66f451Sopenharmony_ci}
59