1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43#include "libbb.h"
44#ifdef __linux__
45# include <sys/sysinfo.h>
46#endif
47
48#ifndef FSHIFT
49# define FSHIFT 16
50#endif
51#define FIXED_1 (1 << FSHIFT)
52#define LOAD_INT(x) (unsigned)((x) >> FSHIFT)
53#define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1 - 1)) * 100)
54
55int uptime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
56int uptime_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
57{
58 unsigned updays, uphours, upminutes;
59 unsigned opts;
60 struct sysinfo info;
61 struct tm *current_time;
62 time_t current_secs;
63
64 opts = getopt32(argv, "s");
65
66 time(¤t_secs);
67 sysinfo(&info);
68
69 if (opts)
70 current_secs -= info.uptime;
71
72 current_time = localtime(¤t_secs);
73
74 if (opts) {
75 printf("%04u-%02u-%02u %02u:%02u:%02u\n",
76 current_time->tm_year + 1900, current_time->tm_mon + 1, current_time->tm_mday,
77 current_time->tm_hour, current_time->tm_min, current_time->tm_sec
78 );
79
80
81
82
83
84 return EXIT_SUCCESS;
85 }
86
87 printf(" %02u:%02u:%02u up ",
88 current_time->tm_hour, current_time->tm_min, current_time->tm_sec
89 );
90 updays = (unsigned) info.uptime / (unsigned)(60*60*24);
91 if (updays != 0)
92 printf("%u day%s, ", updays, (updays != 1) ? "s" : "");
93 upminutes = (unsigned) info.uptime / (unsigned)60;
94 uphours = (upminutes / (unsigned)60) % (unsigned)24;
95 upminutes %= 60;
96 if (uphours != 0)
97 printf("%2u:%02u", uphours, upminutes);
98 else
99 printf("%u min", upminutes);
100
101#if ENABLE_FEATURE_UPTIME_UTMP_SUPPORT
102 {
103 struct utmpx *ut;
104 unsigned users = 0;
105 while ((ut = getutxent()) != NULL) {
106 if ((ut->ut_type == USER_PROCESS) && (ut->ut_user[0] != '\0'))
107 users++;
108 }
109 printf(", %u users", users);
110 }
111#endif
112
113 printf(", load average: %u.%02u, %u.%02u, %u.%02u\n",
114 LOAD_INT(info.loads[0]), LOAD_FRAC(info.loads[0]),
115 LOAD_INT(info.loads[1]), LOAD_FRAC(info.loads[1]),
116 LOAD_INT(info.loads[2]), LOAD_FRAC(info.loads[2]));
117
118 return EXIT_SUCCESS;
119}
120