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