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