1 /* This is a trivial uptime program. I hereby release this program 2 * into the public domain. I disclaim any responsibility for this 3 * program --- use it at your own risk. (as if there were any.. ;-) 4 * -michaelkjohnson (johnsonm (at) sunsite.unc.edu) 5 * 6 * Modified by Larry Greenfield to give a more traditional output, 7 * count users, etc. (greenfie (at) gauss.rutgers.edu) 8 * 9 * Modified by mkj again to fix a few tiny buglies. 10 * 11 * Modified by J. Cowley to add printing the uptime message to a 12 * string (for top) and to optimize file handling. 19 Mar 1993. 13 * 14 */ 15 16 #include <stdio.h> 17 #include <stdlib.h> 18 #include <string.h> 19 #include <fcntl.h> 20 #include <unistd.h> 21 #include <time.h> 22 #include <utmp.h> 23 #include <sys/ioctl.h> 24 #include "whattime.h" 25 #include "sysinfo.h" 26 27 static char buf[128]; 28 static double av[3]; 29 30 char *sprint_uptime(void) 31 { 32 struct utmp *utmpstruct; 33 int upminutes, uphours, updays; 34 int pos; 35 struct tm *realtime; 36 time_t realseconds; 37 int numuser; 38 double uptime_secs, idle_secs; 39 40 /* first get the current time */ 41 42 time(&realseconds); 43 realtime = localtime(&realseconds); 44 pos = sprintf(buf, " %02d:%02d:%02d ", 45 realtime->tm_hour, realtime->tm_min, realtime->tm_sec); 46 47 /* read and calculate the amount of uptime */ 48 49 uptime(&uptime_secs, &idle_secs); 50 51 updays = (int)uptime_secs / (60 * 60 * 24); 52 strcat(buf, "up "); 53 pos += 3; 54 if (updays) 55 pos += 56 sprintf(buf + pos, "%d day%s, ", updays, 57 (updays != 1) ? "s" : ""); 58 upminutes = (int)uptime_secs / 60; 59 uphours = upminutes / 60; 60 uphours = uphours % 24; 61 upminutes = upminutes % 60; 62 if (uphours) 63 pos += sprintf(buf + pos, "%2d:%02d, ", uphours, upminutes); 64 else 65 pos += sprintf(buf + pos, "%d min, ", upminutes); 66 67 /* count the number of users */ 68 69 numuser = 0; 70 setutent(); 71 while ((utmpstruct = getutent())) { 72 if ((utmpstruct->ut_type == USER_PROCESS) && 73 (utmpstruct->ut_name[0] != '\0')) 74 numuser++; 75 } 76 endutent(); 77 78 pos += 79 sprintf(buf + pos, "%2d user%s, ", numuser, 80 numuser == 1 ? "" : "s"); 81 82 loadavg(&av[0], &av[1], &av[2]); 83 84 pos += sprintf(buf + pos, " load average: %.2f, %.2f, %.2f", 85 av[0], av[1], av[2]); 86 87 return buf; 88 } 89 90 void print_uptime(void) 91 { 92 printf("%s\n", sprint_uptime()); 93 } 94