uptime.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. * uptime - Print system uptime
  7. */
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <unistd.h>
  12. #include <time.h>
  13. #include <sys/time.h>
  14. void print_time(void) {
  15. struct timeval now;
  16. struct tm * timeinfo;
  17. char clocktime[10];
  18. gettimeofday(&now, NULL);
  19. timeinfo = localtime((time_t *)&now.tv_sec);
  20. strftime(clocktime, 80, "%H:%M:%S", timeinfo);
  21. printf(" %s ", clocktime);
  22. }
  23. #define MINUTE (60)
  24. #define HOUR (60 * MINUTE)
  25. #define DAY (24 * HOUR)
  26. void print_seconds(int seconds) {
  27. if (seconds > DAY) {
  28. int days = seconds / DAY;
  29. seconds -= DAY * days;
  30. printf("%d day%s, ", days, days != 1 ? "s" : "");
  31. }
  32. if (seconds > HOUR) {
  33. int hours = seconds / HOUR;
  34. seconds -= HOUR * hours;
  35. int minutes = seconds / MINUTE;
  36. printf("%2d:%02d", hours, minutes);
  37. return;
  38. } else if (seconds > MINUTE) {
  39. int minutes = seconds / MINUTE;
  40. printf("%d minute%s, ", minutes, minutes != 1 ? "s" : "");
  41. seconds -= MINUTE * minutes;
  42. }
  43. printf("%2d second%s", seconds, seconds != 1 ? "s" : "");
  44. }
  45. void print_uptime(void) {
  46. FILE * f = fopen("/proc/uptime", "r");
  47. if (!f) return;
  48. int seconds;
  49. char buf[1024] = {0};
  50. fgets(buf, 1024, f);
  51. char * dot = strchr(buf, '.');
  52. *dot = '\0';
  53. dot++;
  54. dot[3] = '\0';
  55. seconds = atoi(buf);
  56. printf("up ");
  57. print_seconds(seconds);
  58. }
  59. void show_usage(int argc, char * argv[]) {
  60. printf(
  61. "uptime - display system uptime information\n"
  62. "\n"
  63. "usage: %s [-p]\n"
  64. "\n"
  65. " -p \033[3mshow just the uptime info\033[0m\n"
  66. " -? \033[3mshow this help text\033[0m\n"
  67. "\n", argv[0]);
  68. }
  69. int main(int argc, char * argv[]) {
  70. int just_pretty_uptime = 0;
  71. int opt;
  72. while ((opt = getopt(argc, argv, "?p")) != -1 ) {
  73. switch (opt) {
  74. case 'p':
  75. just_pretty_uptime = 1;
  76. break;
  77. case '?':
  78. show_usage(argc, argv);
  79. return 0;
  80. }
  81. }
  82. if (!just_pretty_uptime)
  83. print_time();
  84. print_uptime();
  85. printf("\n");
  86. return 0;
  87. }