uptime.c 863 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /* See LICENSE file for copyright and license details. */
  2. #include <err.h>
  3. #include <time.h>
  4. #include <stdio.h>
  5. #include <stdint.h>
  6. #include "../lib/util.h"
  7. #if defined(CLOCK_BOOTTIME)
  8. # define UPTIME_FLAG CLOCK_BOOTTIME
  9. # define STR_UPTIME_FLAG "CLOCK_BOOTTIME"
  10. #elif defined(CLOCK_UPTIME)
  11. # define UPTIME_FLAG CLOCK_UPTIME
  12. # define STR_UPTIME_FLAG "CLOCK_UPTIME"
  13. #else
  14. # define UPTIME_FLAG CLOCK_MONOTONIC
  15. # define STR_UPTIME_FLAG "CLOCK_MONOTONIC"
  16. #endif
  17. void
  18. uptime(char *out,
  19. const char __unused *_a,
  20. uint32_t __unused _i,
  21. void __unused *_p)
  22. {
  23. uintmax_t h, m;
  24. struct timespec uptime;
  25. if (clock_gettime(UPTIME_FLAG, &uptime) < 0) {
  26. warnx("clock_gettime(%s)", STR_UPTIME_FLAG);
  27. ERRRET(out);
  28. }
  29. SAFE_ASSIGN(h, uptime.tv_sec / 3600);
  30. SAFE_ASSIGN(m, uptime.tv_sec % 3600 / 60);
  31. bprintf(out, "%juh %jum", h, m);
  32. }