uptime.c 891 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* See LICENSE file for copyright and license details. */
  2. #include <stdio.h>
  3. #include "../util.h"
  4. static const char *
  5. format(int uptime)
  6. {
  7. int h, m;
  8. h = uptime / 3600;
  9. m = (uptime - h * 3600) / 60;
  10. return bprintf("%dh %dm", h, m);
  11. }
  12. #if defined(__linux__)
  13. #include <sys/sysinfo.h>
  14. const char *
  15. uptime(void)
  16. {
  17. int uptime;
  18. struct sysinfo info;
  19. sysinfo(&info);
  20. uptime = info.uptime;
  21. return format(uptime);
  22. }
  23. #elif defined(__OpenBSD__)
  24. #include <sys/sysctl.h>
  25. #include <sys/time.h>
  26. const char *
  27. uptime(void)
  28. {
  29. int mib[2], uptime;
  30. size_t size;
  31. time_t now;
  32. struct timeval boottime;
  33. time(&now);
  34. mib[0] = CTL_KERN;
  35. mib[1] = KERN_BOOTTIME;
  36. size = sizeof(boottime);
  37. if (sysctl(mib, 2, &boottime, &size, NULL, 0) < 0) {
  38. warn("sysctl 'KERN_BOOTTIME':");
  39. return NULL;
  40. }
  41. uptime = now - boottime.tv_sec;
  42. return format(uptime);
  43. }
  44. #endif