feat(macos): add uptime

This commit is contained in:
utox39
2025-02-24 00:28:17 +01:00
parent e7af5f4d28
commit 6a5203ab7e

View File

@@ -1,4 +1,12 @@
const std = @import("std"); const std = @import("std");
const c_libproc = @cImport(@cInclude("libproc.h"));
const c_sysctl = @cImport(@cInclude("sys/sysctl.h"));
pub const SystemUptime = struct {
days: i8,
hours: i8,
minutes: i8,
};
pub fn getUsername(allocator: std.mem.Allocator) ![]u8 { pub fn getUsername(allocator: std.mem.Allocator) ![]u8 {
const username = try std.process.getEnvVarOwned(allocator, "USER"); const username = try std.process.getEnvVarOwned(allocator, "USER");
@@ -13,3 +21,36 @@ pub fn getHostname(allocator: std.mem.Allocator) ![]u8 {
return hostname; return hostname;
} }
pub fn getSystemUptime() !SystemUptime {
const seconds_per_day: f64 = 86400.0;
var boot_time: c_libproc.struct_timeval = undefined;
var size: usize = @sizeOf(c_libproc.struct_timeval);
var uptime_ns: f64 = 0.0;
var name = [_]c_int{ c_sysctl.CTL_KERN, c_sysctl.KERN_BOOTTIME };
if (c_sysctl.sysctl(&name, 2, &boot_time, &size, null, 0) == 0) {
const boot_seconds = @as(f64, @floatFromInt(boot_time.tv_sec));
const now_seconds = @as(f64, @floatFromInt(std.time.timestamp()));
uptime_ns = now_seconds - boot_seconds;
} else {
return error.UnableToGetSystemUptime;
}
var remainig_seconds: f64 = uptime_ns;
const days: f64 = @floor(remainig_seconds / seconds_per_day);
remainig_seconds = (remainig_seconds / seconds_per_day) - days;
const hours = @floor(remainig_seconds * 24);
remainig_seconds = (remainig_seconds * 24) - hours;
const minutes = @floor((remainig_seconds * 3600) / 60);
return SystemUptime{
.days = @as(i8, @intFromFloat(days)),
.hours = @as(i8, @intFromFloat(hours)),
.minutes = @as(i8, @intFromFloat(minutes)),
};
}