xref: /aosp_15_r20/external/toybox/toys/other/uptime.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* uptime.c - Tell how long the system has been running.
2  *
3  * Copyright 2012 Elie De Brauwer <[email protected]>
4  * Copyright 2012 Luis Felipe Strano Moraes <[email protected]>
5  * Copyright 2013 Jeroen van Rijn <[email protected]>
6 
7 USE_UPTIME(NEWTOY(uptime, ">0ps", TOYFLAG_USR|TOYFLAG_BIN))
8 
9 config UPTIME
10   bool "uptime"
11   default y
12   help
13     usage: uptime [-ps]
14 
15     Tell the current time, how long the system has been running, the number
16     of users, and the system load averages for the past 1, 5 and 15 minutes.
17 
18     -p	Pretty (human readable) uptime
19     -s	Since when has the system been up?
20 */
21 
22 #define FOR_uptime
23 #include "toys.h"
24 
uptime_main(void)25 void uptime_main(void)
26 {
27   struct sysinfo info;
28   time_t t;
29   struct tm *tm;
30   unsigned int weeks, days, hours, minutes;
31   struct utmpx *entry;
32   int users = 0;
33 
34   // Obtain the data we need.
35   sysinfo(&info);
36   time(&t);
37 
38   // Just show the time of boot?
39   if (FLAG(s)) {
40     t -= info.uptime;
41     tm = localtime(&t);
42     strftime(toybuf, sizeof(toybuf), "%F %T", tm);
43     xputs(toybuf);
44     return;
45   }
46 
47   // Current time
48   tm = localtime(&t);
49   // Uptime
50   info.uptime /= 60;
51   minutes = info.uptime%60;
52   info.uptime /= 60;
53   hours = info.uptime%24;
54   days = info.uptime/24;
55 
56   if (FLAG(p)) {
57     weeks = days/7;
58     days %= 7;
59     xprintf("up %d week%s, %d day%s, %d hour%s, %d minute%s, ",
60         weeks, (weeks!=1)?"s":"",
61         days, (days!=1)?"s":"",
62         hours, (hours!=1)?"s":"",
63         minutes, (minutes!=1)?"s":"");
64   } else {
65     xprintf(" %02d:%02d:%02d up ", tm->tm_hour, tm->tm_min, tm->tm_sec);
66     if (days) xprintf("%d day%s, ", days, (days!=1)?"s":"");
67     if (hours) xprintf("%2d:%02d, ", hours, minutes);
68     else printf("%d min, ", minutes);
69 
70     // Obtain info about logged on users
71     setutxent();
72     while ((entry = getutxent())) if (entry->ut_type == USER_PROCESS) users++;
73     endutxent();
74     printf(" %d user%s, ", users, (users!=1) ? "s" : "");
75   }
76 
77   printf(" load average: %.02f, %.02f, %.02f\n", info.loads[0]/65536.0,
78     info.loads[1]/65536.0, info.loads[2]/65536.0);
79 }
80