linux 查看系统运行时间 (从开机当现在的开机时间)
1.uptime命令
输出:16:11:40 up 59 days, 4:21, 2 users, load average: 0.00, 0.01, 0.00
2.查看/proc/uptime文件计算系统启动时间
cat /proc/uptime
输出: 5113396.94 575949.85
第一数字即是系统已运行的时间5113396.94 秒,运用系统工具date即可算出系统启动时间
代码:
date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"
输出: 2008-11-09 11:50:31
3.查看/proc/uptime文件计算系统运行时间
代码:
cat /proc/uptime| awk -F. '{run_days=$1 / 86400;run_hour=($1 % 86400)/3600;run_minute=($1 % 3600)/60;run_second=$1 % 60;printf("系统已运行:%d天%d时%d分%d秒",run_days,run_hour,run_minute,run_second)}'
输出:系统已运行:59天4时13分9秒
这样你就能轻松地应用Linux查看系统时间。
c代码:
struct sysinfo { long uptime; /* Seconds since boot */ unsigned long loads[3]; /* 1, 5, and 15 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 */ unsigned long totalhigh; /* Total high memory size */ unsigned long freehigh; /* Available high memory size */ unsigned int mem_unit; /* Memory unit size in bytes */ char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */ };
#include <stdio.h> #include <time.h> #include <stdio.h> #include <errno.h> #include <linux/unistd.h> /* for _syscallX macros/related stuff */ #include <linux/kernel.h> /* for struct sysinfo */ #include <sys/sysinfo.h> long get_uptime() { struct sysinfo s_info; int error; error = sysinfo(&s_info); if(error != 0) { printf("code error = %d ", error); } return s_info.uptime; } long out_sys(){ /* Conversion constants. */ const long minute = 60; const long hour = minute * 60; const long day = hour * 24; const double megabyte = 1024 * 1024; /* Obtain system statistics. */ struct sysinfo si; sysinfo (&si); /* Summarize interesting values. */ printf ("system uptime : %ld days, %ld:%02ld:%02ld ", si.uptime / day, (si.uptime % day) / hour, (si.uptime % hour) / minute, si.uptime % minute); printf ("total RAM : %5.1f MB ", si.totalram / megabyte); printf ("free RAM : %5.1f MB ", si.freeram / megabyte); printf ("process count : %d ", si.procs); } int main(int argc, char* argv[]) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); printf("tv_sec=%llu tv_nsec=%llu uptime time:%llu ", (unsigned long long)t.tv_sec, (unsigned long long)t.tv_nsec, get_uptime()); out_sys(); return 0; }