uptime.c (1755B)
1 /* see LICENSE file for copyright and license details */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <time.h> 7 #include <utmpx.h> 8 9 #include "config.h" 10 #include "sysinfo.h" 11 #include "util.h" 12 13 static void 14 usage(void) 15 { 16 eprintf("usage: %s\n", argv0); 17 } 18 19 // ?man uptime: show system uptime 20 // ?man display how long the system has been running and load averages 21 int 22 main(int argc, char *argv[]) 23 { 24 struct utmpx utx; 25 FILE *ufp; 26 long uptime; 27 double loads[3]; 28 time_t tmptime; 29 struct tm *now; 30 unsigned int days, hours, minutes; 31 int nusers = 0; 32 size_t n; 33 34 ARGBEGIN 35 { 36 default: 37 usage(); 38 } 39 ARGEND; 40 41 if (argc) 42 usage(); 43 44 if (get_uptime(&uptime) < 0) 45 eprintf("get_uptime:"); 46 if (get_loads(loads) < 0) 47 eprintf("get_loads:"); 48 49 time(&tmptime); 50 now = localtime(&tmptime); 51 printf(" %02d:%02d:%02d up ", now->tm_hour, now->tm_min, now->tm_sec); 52 53 uptime /= 60; 54 minutes = uptime % 60; 55 uptime /= 60; 56 hours = uptime % 24; 57 days = uptime / 24; 58 if (days) 59 printf("%d day%s, ", days, days != 1 ? "s" : ""); 60 if (hours) 61 printf("%2d:%02d, ", hours, minutes); 62 else 63 printf("%d min, ", minutes); 64 65 if ((ufp = fopen(UTMP_PATH, "r"))) { 66 while ((n = fread(&utx, sizeof(utx), 1, ufp)) > 0) { 67 if (!utx.ut_user[0]) 68 continue; 69 if (utx.ut_type != USER_PROCESS) 70 continue; 71 nusers++; 72 } 73 if (ferror(ufp)) 74 eprintf("%s: read error:", UTMP_PATH); 75 fclose(ufp); 76 printf(" %d user%s, ", nusers, nusers != 1 ? "s" : ""); 77 } 78 79 printf(" load average: %.02f, %.02f, %.02f\n", loads[0], loads[1], loads[2]); 80 81 if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) 82 return 1; 83 84 return 0; 85 }