linux获取系统启动时间
Linux 获取 时间 系统启动
2023-09-14 08:59:08 时间
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 }
测试结果如下所:
相关文章
- Linux硬盘镜像获取与还原(dd、AccessData FTK Imager)
- linux中获取系统时间的几种方法
- 在Linux上使用logwatch分析监控日志文件
- Linux获取进程执行时间
- 【Linux基础】linux下的stdin,stdout和stderr理解
- Linux基础之linux服务器服务器间拷贝文件
- Linux装B命令
- Linux - 获取命令帮助信息
- linux(ubuntu21.10):apt方式安装redis6.0.15
- linux shell数组定义、元素获取及其长度获取
- 【Linux 内核 内存管理】物理分配页 ⑧ ( __alloc_pages_slowpath 慢速路径调用函数源码分析 | 获取首选内存区域 | 异步回收内存页 | 最低水线也分配 | 直接分配 )
- 记录Linux启动流程的工具bootchart
- linux python3获取ip地址
- 进程间通信之-共享内存Shared Memory--linux内核剖析(十一)
- L83.linux命令每日一练 -- 第11章 Linux系统管理命令 -- ipcs和ipcrm
- L60.linux命令每日一练 -- 第九章 Linux进程管理命令 -- top和nice
- 嵌入式Linux开发,Ubuntu下交叉编译内核报错:error while loading shared libraries: /lib/x86_64-linux-gnu/libc++.so:
- linux常用命令
- Linux namespace命名空间
- 周立功arm linux教程,极速搭建周立功IMX287A ARM Linux开发环境
- Linux:Security: random: RANDOM_TRUST_CPU;random.trust_cpu;entropy;随机熵
- Linux通过域名获取ip工具