1 #include <time.h>
2 #include <errno.h>
3 #include <sys/sysctl.h>
4 
uptime(void)5 long uptime(void)
6 {
7     struct timeval boottime;
8     size_t len = sizeof(boottime);
9     int mib[2] = { CTL_KERN, KERN_BOOTTIME };
10     if (sysctl(mib, 2, &boottime, &len, NULL, 0) < 0)
11     {
12         return -1L;
13     }
14     time_t bsec = boottime.tv_sec, csec = time(NULL);
15 
16     return (long) difftime(csec, bsec);
17 }
18