free.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2015-2018 K. Lange
  5. *
  6. * free - Show free / used / total RAM
  7. */
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <unistd.h>
  11. void show_usage(int argc, char * argv[]) {
  12. printf(
  13. "free - show available memory\n"
  14. "\n"
  15. "usage: %s [-utk?]\n"
  16. "\n"
  17. " -u \033[3mshow used instead of free\033[0m\n"
  18. " -t \033[3minclude a total\033[0m\n"
  19. " -k \033[3muse kilobytes instead of megabytes\033[0m\n"
  20. " -? \033[3mshow this help text\033[0m\n"
  21. "\n", argv[0]);
  22. }
  23. int main(int argc, char * argv[]) {
  24. int show_used = 0;
  25. int use_kilobytes = 0;
  26. int show_total = 0;
  27. int c;
  28. while ((c = getopt(argc, argv, "utk?")) != -1) {
  29. switch (c) {
  30. case 'u':
  31. show_used = 1;
  32. break;
  33. case 't':
  34. show_total = 1;
  35. break;
  36. case 'k':
  37. use_kilobytes = 1;
  38. break;
  39. case '?':
  40. show_usage(argc, argv);
  41. return 0;
  42. }
  43. }
  44. const char * unit = "kB";
  45. FILE * f = fopen("/proc/meminfo", "r");
  46. if (!f) return 1;
  47. int total, free, used;
  48. char buf[1024] = {0};
  49. fgets(buf, 1024, f);
  50. char * a, * b;
  51. a = strchr(buf, ' ');
  52. a++;
  53. b = strchr(a, '\n');
  54. *b = '\0';
  55. total = atoi(a);
  56. fgets(buf, 1024, f);
  57. a = strchr(buf, ' ');
  58. a++;
  59. b = strchr(a, '\n');
  60. *b = '\0';
  61. free = atoi(a);
  62. //fscanf(f, "MemTotal: %d kB\nMemFree: %d kB\n", &total, &free);
  63. used = total - free;
  64. if (!use_kilobytes) {
  65. unit = "MB";
  66. free /= 1024;
  67. used /= 1024;
  68. total /= 1024;
  69. }
  70. if (show_used) {
  71. printf("%d %s", used, unit);
  72. } else {
  73. printf("%d %s", free, unit);
  74. }
  75. if (show_total) {
  76. printf(" / %d %s", total, unit);
  77. }
  78. printf("\n");
  79. return 0;
  80. }