1. Preface
Time is very important to the operating system, from the kernel level to the application layer, the expression of time and the accuracy of each department is the same. The Linux kernel uses a constant called Jiffes to calculate the timestamp. The application layer has time, getdaytime and other functions. Today needs to get the system start time in the application, Baidu a bit, through the sysinfo in the uptime can calculate the system start time.
2. SysInfo structure
The SYSINFO structure maintains the information of the system startup, including the time of startup to the present, the available memory space, the shared memory space, the number of processes, etc. The man sysinfo gets the result as follows:
1structSysInfo {2Long uptime;/*Seconds since boot*/3 unsignedLong loads[3];/*1, 5, and minute load averages*/4 unsignedLong Totalram;/*Total usable main memory size*/5 unsignedLong Freeram;/*Available Memory Size*/6 unsignedLong Sharedram;/*Amount of Shared memory*/7 unsignedLong Bufferram;/*Memory used by buffers*/8 unsignedlong totalswap; /* Total swap space size */< Span style= "COLOR: #008080" > 9 unsigned long freeswap; /* swap space still available */10 unsigned short procs; /* number of current processes */11 char _f[22"; /* Pads structure to bytes */12};
3. Get the system boot time
SysInfo gets the number of seconds that the system has booted to the present time, minus the number of seconds in the current period, which is the system startup time. The program looks like this:
1 #include <stdio.h>2 #include <sys/sysinfo.h>3 #include <time.h>4 #include <errno.h>56StaticIntPrint_system_boot_time ()7{8structSysInfo info;9 time_t cur_time =0;Ten time_t boot_time =0;11struct TM *ptm =NULL;12if (SysInfo (&Info)) {fprintf (stderr,"Failed to get SysInfo, errno:%u, reason:%s\n",14errno, Strerror (errno));15Return-1;16}Time (&Cur_time);18if (Cur_time >Info.uptime) {Boot_time = Cur_time-Info.uptime;20}21stElse{Boot_time = Info.uptime-Cur_time;23}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);27Return0; 28 }29 30 int main () 31 Span style= "COLOR: #000000" >{32 if (print_system_boot_ Time ()! = 0) {33 return-1; }35 return 0;
The test results are as follows:
Linux Get system Boot time