Something similar to linux
cat /proc/uptime
which returns the uptime in seconds, and preferably not parsing uptime(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).
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With