linux獲取系統啟動時間


1、前言

  時間對操作系統來說非常重要,從內核級到應用層,時間的表達方式及精度各部相同。linux內核里面用一個名為jiffes的常量來計算時間戳。應用層有time、getdaytime等函數。今天需要在應用程序獲取系統的啟動時間,百度了一下,通過sysinfo中的uptime可以計算出系統的啟動時間。

2、sysinfo結構

  sysinfo結構保持了系統啟動后的信息,主要包括啟動到現在的時間,可用內存空間、共享內存空間、進程的數目等。man sysinfo得到結果如下所示:

 1 struct sysinfo {  2 long uptime; /* Seconds since boot */  3 unsigned long loads[3]; /* 1, 5, and 15 minute load averages */  4 unsigned long totalram; /* Total usable main memory size */  5 unsigned long freeram; /* Available memory size */  6 unsigned long sharedram; /* Amount of shared memory */  7 unsigned long bufferram; /* Memory used by buffers */  8 unsigned long totalswap; /* Total swap space size */  9 unsigned long freeswap; /* swap space still available */ 10 unsigned short procs; /* Number of current processes */ 11 char _f[22]; /* Pads structure to 64 bytes */ 12 };

3、獲取系統啟動時間

  通過sysinfo獲取系統啟動到現在的秒數,用當前時間減去這個秒數即系統的啟動時間。程序如下所示:

 1 #include <stdio.h>  2 #include <sys/sysinfo.h>  3 #include <time.h>  4 #include <errno.h>  5  6 static int print_system_boot_time()  7 {  8 struct sysinfo info;  9 time_t cur_time = 0; 10 time_t boot_time = 0; 11 struct tm *ptm = NULL; 12 if (sysinfo(&info)) { 13 fprintf(stderr, "Failed to get sysinfo, errno:%u, reason:%s\n", 14  errno, strerror(errno)); 15 return -1; 16  } 17 time(&cur_time); 18 if (cur_time > info.uptime) { 19 boot_time = cur_time - info.uptime; 20  } 21 else { 22 boot_time = info.uptime - cur_time; 23  } 24 ptm = gmtime(&boot_time); 25 printf("System boot time: %d-%-d-%d %d:%d:%d\n", ptm->tm_year + 1900, 26 ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); 27 return 0; 28 } 29 30 int main() 31 { 32 if (print_system_boot_time() != 0) { 33 return -1; 34  } 35 return 0; 36 }

測試結果如下所:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM