Xinqi Bao's Git

Refactor swap.c to use getline() instead of buf-filling
[slstatus.git] / components / uptime.c
index 8a04b92..f97809d 100644 (file)
@@ -1,45 +1,61 @@
 /* See LICENSE file for copyright and license details. */
 #include <stdio.h>
-#if defined(__linux__)
-#include <sys/sysinfo.h>
-#elif defined(__OpenBSD__)
-#include <sys/sysctl.h>
-#include <sys/time.h>
-#endif
 
 #include "../util.h"
 
-const char *
-uptime(void)
+static const char *
+format(int uptime)
 {
-       int h;
-       int m;
-       int uptime = 0;
+       int h, m;
+
+       h = uptime / 3600;
+       m = (uptime - h * 3600) / 60;
+
+       return bprintf("%dh %dm", h, m);
+}
+
 #if defined(__linux__)
-       struct sysinfo info;
+       #include <sys/sysinfo.h>
 
-       sysinfo(&info);
-       uptime = info.uptime;
+       const char *
+       uptime(void)
+       {
+               int uptime;
+               struct sysinfo info;
+
+               sysinfo(&info);
+               uptime = info.uptime;
+
+               return format(uptime);
+       }
 #elif defined(__OpenBSD__)
-       int mib[2];
-       size_t size;
-       time_t now;
-       struct timeval boottime;
+       #include <errno.h>
+       #include <string.h>
+       #include <sys/sysctl.h>
+       #include <sys/time.h>
+
+       const char *
+       uptime(void)
+       {
+               int mib[2], uptime;
+               size_t size;
+               time_t now;
+               struct timeval boottime;
 
-       time(&now);
+               time(&now);
 
-       mib[0] = CTL_KERN;
-       mib[1] = KERN_BOOTTIME;
+               mib[0] = CTL_KERN;
+               mib[1] = KERN_BOOTTIME;
 
-       size = sizeof(boottime);
+               size = sizeof(boottime);
+
+               if (sysctl(mib, 2, &boottime, &size, NULL, 0) < 0) {
+                       warn("sysctl 'KERN_BOOTTIME':");
+                       return NULL;
+               }
 
-       if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1)
                uptime = now - boottime.tv_sec;
-       else
-               return NULL;
-#endif
-       h = uptime / 3600;
-       m = (uptime - h * 3600) / 60;
 
-       return bprintf("%dh %dm", h, m);
-}
+               return format(uptime);
+       }
+#endif