micro-utils/src/uptime.c
2024-07-09 11:02:46 +03:00

60 lines
1.2 KiB
C

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include "config.h"
#if defined(CLOCK_BOOTTIME)
#define CLOCK CLOCK_BOOTTIME
#elif defined(CLOCK_UPTIME)
#define CLOCK CLOCK_UPTIME
#elif defined(__APPLE__)
#define CLOCK CLOCK_MONOTONIC
#endif
int main(void) {
/* Now date */
time_t current_secs;
time(&current_secs);
struct tm *current_time = localtime(&current_secs);
printf("%02d:%02d:%02d ", current_time->tm_hour, current_time->tm_min, current_time->tm_sec);
/* How long system has beep up */
struct timespec uptime;
if (clock_gettime(CLOCK, &uptime) != -1) {
int days = uptime.tv_sec / 86400;
int hours = uptime.tv_sec / 3600;
int mins = (uptime.tv_sec / 60) - (uptime.tv_sec / 3600 * 60);
printf("up:");
if (days > 0)
printf(" %d days", days);
else if (hours > 0)
printf(" %d hours", hours);
printf(" %d mins", mins);
}
#ifdef UPTIME_LOADAVG
/* Print 1, 5 and 15 minute load averages */
double avg[3] = {0, 0, 0};
if (getloadavg(avg, sizeof(avg) / sizeof(avg[0])) < 0) {
fprintf(stderr, "uptime: %s\n", strerror(errno));
return 1;
}
printf(" load average: %.2f %.2f %.2f", avg[0], avg[1], avg[2]);
#endif
putchar('\n');
return 0;
}