思路是通過讀取/proc/uptime獲得系統啟動時長。
使用指令cat /proc/uptime
通過man proc可以看到如下的資訊:
/proc/uptime:This file contains two numbers: the uptime of the system (seconds), and the amount of time spent in idle process (seconds).
第一個是系統的啟動時長,第二個是系統的空閑時間。兩個的機關都是秒。
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <stdlib.h>
struct timeval timeget(void)
{
struct timeval now;
unsigned char timestr[] = {};
unsigned char uptimestr[] = {};
unsigned char * dotaddr;
unsigned long second;
char error = ;
FILE * timefile = NULL;
timefile = fopen("/proc/uptime", "r");
if(!timefile)
{
printf("[%s:line:%d] error opening '/proc/uptime'",__FILE__,__LINE__);
error = ;
goto out;
}
if( (fread(timestr, sizeof(char), , timefile)) == )
{
printf("[%s:line:%d] read '/proc/uptime' error",__FILE__,__LINE__);
error = ;
goto out;
}
dotaddr = strchr(timestr, '.');
if((dotaddr - timestr + ) < )
memcpy(uptimestr, timestr, dotaddr - timestr + );
else
{
printf("[%s:line:%d] uptime string is too long",__FILE__,__LINE__);
error = ;
goto out;
}
uptimestr[dotaddr - timestr + ] = '\0';
out:
if(error)
{
now.tv_sec = ;
now.tv_usec = ;
}
else
{
now.tv_sec = atol(uptimestr);
now.tv_usec = ;
}
fclose(timefile);
return now;
}
int main()
{
struct timeval uptime;
uptime = timeget();
printf("uptime = %lu\n", uptime.tv_sec);
return ;
}
運作結果: