1. Preface
Time is very important to the operating system, from the kernel level to the application layer, the time expression and precision of the same. The Linux kernel uses a constant named Jiffes to compute the timestamp. Application layer has time, getdaytime and other functions. Today, you need to get the boot time of the system in the application, and you can calculate the startup time of the system through the uptime in SysInfo.
2. SysInfo structure
The SYSINFO structure keeps the information after the system starts, mainly including the time it starts up to now, the available memory space, the shared memory space, the number of processes, and so on. The man SysInfo gets the results as follows:
Copy Code code as follows:
struct SysInfo {
Long uptime; /* Seconds since boot * *
unsigned long loads[3]; /* 1, 5, and minute load averages * *
unsigned long totalram; /* Total usable main memory size * *
unsigned long freeram; /* Available Memory Size * *
unsigned long sharedram; /* Amount of shared memory * *
unsigned long bufferram; /* Memory used by buffers *
unsigned long totalswap; /* Total swap space Size * *
unsigned long freeswap; /* Swap space still available * *
unsigned short procs; /* Number of current processes * *
Char _f[22]; * Pads structure to bytes *
3. Get System Start time
Get the system boot to the current number of seconds by SysInfo, minus the number of seconds that is the time the system started. The program looks like this:
Copy Code code as follows:
#include <stdio.h>
#include <sys/sysinfo.h>
#include <time.h>
#include <errno.h>
static int Print_system_boot_time ()
{
struct SysInfo info;
time_t cur_time = 0;
time_t boot_time = 0;
struct TM *ptm = NULL;
if (SysInfo (&info)) {
fprintf (stderr, "Failed to get SysInfo, errno:%u, reason:%s\n",
errno, Strerror (errno));
return-1;
}
Time (&cur_time);
if (Cur_time > Info.uptime) {
Boot_time = Cur_time-info.uptime;
}
else {
Boot_time = Info.uptime-cur_time;
}
PTM = Gmtime (&boot_time);
printf ("System boot time:%d-%-d-%d%d:%d:%d\n", Ptm->tm_year + 1900,
Ptm->tm_mon + 1, ptm->tm_mday, Ptm->tm_hour, Ptm->tm_min, ptm->tm_sec);
return 0;
}
int main ()
{
if (print_system_boot_time ()!= 0) {
return-1;
}
return 0;
}
The test results are as follows: