OSX: programmatically get uptime?

2020-02-10 04:43发布

问题:

Something similar to linux

cat /proc/uptime

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

回答1:

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).



回答2:

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);
}


回答3:

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.



回答4:

correct way:

CFTimeInterval getSystemUptime(void)
{
    enum { NANOSECONDS_IN_SEC = 1000 * 1000 * 1000 };
    static double multiply = 0;
    if (multiply == 0)
    {
        mach_timebase_info_data_t s_timebase_info;
        kern_return_t result = mach_timebase_info(&s_timebase_info);
        assert(result == noErr);
        // multiply to get value in the nano seconds
        multiply = (double)s_timebase_info.numer / (double)s_timebase_info.denom;
        // multiply to get value in the seconds
        multiply /= NANOSECONDS_IN_SEC;
    }
    return mach_absolute_time() * multiply;
}

also you could use CACurrentMediaTime() from QuartzCore.framework (which has same code probably) - Available since OS X v10.5 and iOS 2.0



回答5:

There is a function UpTime declared in DriverServices.h. I believe this is equivalent to another function mach_absolute_time. Both seem to be undocumented.



回答6:

Unfortunately the "sysctl kern.boottime" returns the seconds of the timestamp, not elapsed seconds.. Multiple calls do not increase the second count, but must be seconds from epoc of the boot date itself.



回答7:

A simple Lua script to do exactly what you ask for:

local now=tonumber(io.popen("date +%s"):read())
local boottime=tonumber(io.popen("sysctl -n kern.boottime"):read():match("sec = (%d+)"))
local uptime=now-boottime


标签: macos uptime