How to get reboot time on Mac machine programmatically.

By | May 20, 2020

It is similar implementation as about reboot time as “How to get reboot time on Linux machine programmatically“, but for Mac OSX devices. The code is based on the same sysctl function described already in “sysctl command and function” and “Get kernel information through command line and programmatically“, but using different management information base (MIB) names as parameters: CTL_KERN and KERN_BOOTTIME.


The code itself (lastreboot.cpp):


#include <stdio.h>
#include <sys/sysctl.h>
#include <time.h>
int main(int n, char ** s)
{
   struct timeval boottime;
   size_t len = sizeof(boottime);
   int mib[2] = { CTL_KERN, KERN_BOOTTIME };
   int iError = sysctl(mib, 2, &boottime, &len, NULL, 0);
   if(iError == 0)
   {
      struct tm * utcdatetime;
      time_t timestamp = (const time_t)boottime.tv_sec;
      utcdatetime = gmtime(&timestamp);
      printf("Last reboot UTC time: %s\n",asctime(utcdatetime));
   } else {
      printf("Cannot get last reboot time. Error: %d\n", iError);
   }
   return 0;
}

The output:


# ./lastreboot
Last reboot UTC time: Fri May 15 01:02:46 2020

Leave a Reply

Your email address will not be published. Required fields are marked *