Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX: programmatically get uptime?

Tags:

macos

uptime

Something similar to linux

cat /proc/uptime

which returns the uptime in seconds, and preferably not parsing uptime(1).

like image 203
Mark Harrison Avatar asked Jul 16 '10 22:07

Mark Harrison


3 Answers

The Uptime article on Wikipedia has an interesting lead:

Using sysctl

There is also a method of using sysctl to call the system's last boot time: $ sysctl kern.boottime kern.boottime: { sec = 1271934886, usec = 667779 } Thu Apr 22 12:14:46 2010

Which references sysctl(8), which references sysctl(3).

like image 110
Shaggy Frog Avatar answered Oct 16 '22 23:10

Shaggy Frog


Old question, I know, but I needed to do the same thing so I thought I'd post the code I'm using, which I got from http://cocoadev.com/wiki/FindingUptime

#include <time.h>
#include <errno.h>
#include <sys/sysctl.h>

double uptime()
{
    struct timeval boottime;
    size_t len = sizeof(boottime);
    int mib[2] = { CTL_KERN, KERN_BOOTTIME };
    if( sysctl(mib, 2, &boottime, &len, NULL, 0) < 0 )
    {
        return -1.0;
    }
    time_t bsec = boottime.tv_sec, csec = time(NULL);

    return difftime(csec, bsec);
}
like image 20
Bleyddyn Avatar answered Oct 16 '22 21:10

Bleyddyn


If anyone is trying to do this programmatically using sysctl.h and is expecting a string back like what you see in the command line, the returned value that I get is a 16 byte array, not a string:

sysctlbyname("kern.boottime", value, &size, NULL, 0);

An example for what gets put into value in hex starting from the [0] index:

a9 af c6 4e 0 0 0 0 0 0 0 0 28 be 92 55

The first 4 bytes (maybe the first 8, won't know until Jan 2012) is the epoch time in little endian byte order.

like image 34
Jon Avatar answered Oct 16 '22 23:10

Jon