Last active
January 14, 2025 22:45
-
-
Save nyg/dbdef21a1a0632c389d4d756d4fc1c0d to your computer and use it in GitHub Desktop.
Get boot time and uptime on macOS in C.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Tested on macOS 10.12. | |
// | |
// Usage: | |
// $ clang uptime.c && ./a.out | |
// boot time (UNIX time): 1502299682.147510 | |
// uptime (seconds): 410563.269028116 | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <stdio.h> | |
#include <sys/sysctl.h> | |
struct timeval get_boottime(); | |
struct timespec get_uptime(); | |
void print_error(); | |
int main(int argc, char** argv) | |
{ | |
struct timeval boottime = get_boottime(); | |
printf("boot time (UNIX time): %li.%06i\n", boottime.tv_sec, boottime.tv_usec); | |
struct timespec uptime = get_uptime(); | |
printf("uptime (seconds): %li.%09li\n", uptime.tv_sec, uptime.tv_nsec); | |
} | |
struct timeval get_boottime() | |
{ | |
struct timeval boottime; | |
int mib[2] = { CTL_KERN, KERN_BOOTTIME }; | |
size_t size = sizeof(boottime); | |
if (0 != sysctl(mib, 2, &boottime, &size, NULL, 0)) | |
{ | |
print_error(); | |
} | |
return boottime; | |
} | |
struct timespec get_uptime() | |
{ | |
struct timespec uptime; | |
if (0 != clock_gettime(CLOCK_MONOTONIC_RAW, &uptime)) | |
{ | |
print_error(); | |
} | |
return uptime; | |
} | |
void print_error() | |
{ | |
printf("%s\n", strerror(errno)); | |
exit(errno); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment