uptime.c 675 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* See LICENSE file for copyright and license details. */
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <sys/sysctl.h>
  6. #include <sys/time.h>
  7. #include "../../util.h"
  8. const char *
  9. uptime(void)
  10. {
  11. int h;
  12. int m;
  13. int uptime = 0;
  14. int mib[2];
  15. size_t size;
  16. time_t now;
  17. struct timeval boottime;
  18. time(&now);
  19. mib[0] = CTL_KERN;
  20. mib[1] = KERN_BOOTTIME;
  21. size = sizeof(boottime);
  22. if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1)
  23. uptime = now - boottime.tv_sec;
  24. else {
  25. fprintf(stderr, "sysctl 'KERN_BOOTTIME': %s\n", strerror(errno));
  26. return NULL;
  27. }
  28. h = uptime / 3600;
  29. m = (uptime - h * 3600) / 60;
  30. return bprintf("%dh %dm", h, m);
  31. }