程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C >> 關於C >> linux用c語言獲取系統啟動時長

linux用c語言獲取系統啟動時長

編輯:關於C

思路是通過讀取/proc/uptime獲得系統啟動時長。
使用命令cat /proc/uptime
這裡寫圖片描述
通過man proc可以看到如下的信息:
喎?/kf/ware/vc/" target="_blank" class="keylink">vcHJvYy91cHRpbWWjulRoaXMgZmlsZSBjb250YWlucyB0d28gbnVtYmVyczogdGhlIHVwdGltZSBvZiB0aGUgc3lzdGVtIChzZWNvbmRzKSwgYW5kIHRoZSBhbW91bnQgb2YgdGltZSBzcGVudCBpbiBpZGxlIHByb2Nlc3MgKHNlY29uZHMpLjxiciAvPg0KtdrSu7j2ysfPtc2ztcTG9LavyrGzpKOstdq2/rj2ysfPtc2ztcS/1c/QyrG85KGjwb249rXEtaXOu7a8ysfD66GjPC9wPg0KPHByZSBjbGFzcz0="brush:java;"> #include #include #include #include struct timeval timeget(void) { struct timeval now; unsigned char timestr[60] = {0}; unsigned char uptimestr[30] = {0}; unsigned char * dotaddr; unsigned long second; char error = 0; FILE * timefile = NULL; timefile = fopen("/proc/uptime", "r"); if(!timefile) { printf("[%s:line:%d] error opening '/proc/uptime'",__FILE__,__LINE__); error = 1; goto out; } if( (fread(timestr, sizeof(char), 60, timefile)) == 0 ) { printf("[%s:line:%d] read '/proc/uptime' error",__FILE__,__LINE__); error = 1; goto out; } dotaddr = strchr(timestr, '.'); if((dotaddr - timestr + 2) < 30) memcpy(uptimestr, timestr, dotaddr - timestr + 2); else { printf("[%s:line:%d] uptime string is too long",__FILE__,__LINE__); error = 1; goto out; } uptimestr[dotaddr - timestr + 2] = '\0'; out: if(error) { now.tv_sec = 0; now.tv_usec = 0; } else { now.tv_sec = atol(uptimestr); now.tv_usec = 0; } fclose(timefile); return now; } int main() { struct timeval uptime; uptime = timeget(); printf("uptime = %lu\n", uptime.tv_sec); return 0; }

運行結果:
這裡寫圖片描述

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved