Xinqi Bao's Git

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