How to get reboot time on Linux machine programmatically.

By | March 2, 2018

The sysinfo system call returns a lot of useful system statistic data: memory usage, number of currently running processes, seconds since last boot. The only argument used by sysinfo is a pointer to a sysinfo structure. The first member of sysinfo structure is uptime which contains number of seconds since last reboot. For more details about sysinfo structure use man command: ‘man sysinfo’. Below presented c++ code which takes uptime and convert it to date and time string.
The output of the application is:


# ./reboottime
Last reboot date and time: 2018-02-26 08:08:58

c++ Code:

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <sys/times.h>
#include <sys/sysinfo.h>
int main(int, char **)
{
        char   szBuffer[32];
        struct sysinfo sys_info;
        sysinfo(&sys_info);
//        printf("Second after last reboot: %llu\n", (unsigned long long)sys_info.uptime);
        time_t currentTime = time(NULL);
//        printf("Current Time: %llu\n", (unsigned long long)currentTime);
        time_t rebootTime = currentTime - sys_info.uptime;
        struct tm * tmrebootTime = localtime(&rebootTime);
        memset(szBuffer,0,32);
        strftime(szBuffer, sizeof(szBuffer), "%Y-%m-%d %H:%M:%S", tmrebootTime); // convert reboot Unix time to string
        printf("Last reboot date and time: %s\n", szBuffer);
        return 0;
}


Leave a Reply

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