morpheus-base

morpheus base system
git clone git://git.2f30.org/morpheus-base
Log | Files | Refs

uptime.c (1452B)


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