feat(linux): add uptime
This commit is contained in:
@@ -1,4 +1,12 @@
|
|||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const c_sysinfo = @cImport(@cInclude("sys/sysinfo.h"));
|
||||||
|
|
||||||
|
/// Structure representing system uptime in days, hours, and minutes.
|
||||||
|
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,35 @@ pub fn getHostname(allocator: std.mem.Allocator) ![]u8 {
|
|||||||
|
|
||||||
return hostname;
|
return hostname;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the system uptime.
|
||||||
|
///
|
||||||
|
/// Uses `sysinfo` to fetch the system uptime and calculates the elapsed time.
|
||||||
|
pub fn getSystemUptime() !SystemUptime {
|
||||||
|
const seconds_per_day: f64 = 86400.0;
|
||||||
|
const hours_per_day: f64 = 24.0;
|
||||||
|
const seconds_per_hour: f64 = 3600.0;
|
||||||
|
const seconds_per_minute: f64 = 60.0;
|
||||||
|
|
||||||
|
var info: c_sysinfo.struct_sysinfo = undefined;
|
||||||
|
if (c_sysinfo.sysinfo(&info) != 0) {
|
||||||
|
return error.SysinfoFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uptime_seconds: f64 = @as(f64, @floatFromInt(info.uptime));
|
||||||
|
|
||||||
|
var remainig_seconds: f64 = uptime_seconds;
|
||||||
|
const days: f64 = @floor(remainig_seconds / seconds_per_day);
|
||||||
|
|
||||||
|
remainig_seconds = (remainig_seconds / seconds_per_day) - days;
|
||||||
|
const hours = @floor(remainig_seconds * hours_per_day);
|
||||||
|
|
||||||
|
remainig_seconds = (remainig_seconds * hours_per_day) - hours;
|
||||||
|
const minutes = @floor((remainig_seconds * seconds_per_hour) / seconds_per_minute);
|
||||||
|
|
||||||
|
return SystemUptime{
|
||||||
|
.days = @as(i8, @intFromFloat(days)),
|
||||||
|
.hours = @as(i8, @intFromFloat(hours)),
|
||||||
|
.minutes = @as(i8, @intFromFloat(minutes)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user