micro-utils/src/procps/uptime/uptime.c

60 lines
1.2 KiB
C
Raw Normal View History

2023-10-24 12:33:08 +00:00
#include <stdio.h>
2024-03-03 13:34:11 +00:00
#include <string.h>
#include <errno.h>
2023-10-24 12:36:13 +00:00
#include <stdlib.h>
2023-10-24 12:33:08 +00:00
#include <time.h>
2023-11-14 20:25:45 +00:00
#include "config.h"
2023-10-24 12:33:08 +00:00
#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);
2024-03-27 19:04:17 +00:00
printf("%02d:%02d:%02d ", current_time->tm_hour, current_time->tm_min, current_time->tm_sec);
2023-10-24 12:33:08 +00:00
/* 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);
2024-01-03 18:00:23 +00:00
else if (hours > 0)
2023-10-24 12:33:08 +00:00
printf(" %d hours", hours);
printf(" %d mins", mins);
}
2023-11-14 20:25:45 +00:00
#ifdef UPTIME_LOADAVG
2023-10-24 12:33:08 +00:00
/* Print 1, 5 and 15 minute load averages */
double avg[3] = {0, 0, 0};
if (getloadavg(avg, sizeof(avg) / sizeof(avg[0])) < 0) {
2024-03-03 13:34:11 +00:00
fprintf(stderr, "uptime: %s\n", strerror(errno));
2023-10-24 12:33:08 +00:00
return 1;
}
2023-11-08 16:47:09 +00:00
printf(" load average: %.2f %.2f %.2f", avg[0], avg[1], avg[2]);
#endif
putchar('\n');
2023-10-24 12:33:08 +00:00
return 0;
}