54 lines
1.2 KiB
Zig
54 lines
1.2 KiB
Zig
const std = @import("std");
|
|
const posix = std.posix;
|
|
const linux = std.os.linux;
|
|
|
|
pub const Event = enum {
|
|
none, // Sentinel
|
|
shutdown, // SIGTERM, SIGINT
|
|
reload, // SIGHUP
|
|
|
|
pub fn fromSignal(sig: i32) ?Event
|
|
{
|
|
const signal: posix.SIG = @enumFromInt(@as(u32, @intCast(sig)));
|
|
|
|
return switch (signal) {
|
|
.TERM,
|
|
.INT => .shutdown,
|
|
.HUP => .reload,
|
|
else => null,
|
|
};
|
|
}
|
|
};
|
|
|
|
pub const SignalFd = struct {
|
|
fd: posix.fd_t,
|
|
|
|
pub fn init() !SignalFd
|
|
{
|
|
var mask = linux.sigemptyset();
|
|
|
|
linux.sigaddset(&mask, posix.SIG.TERM);
|
|
linux.sigaddset(&mask, posix.SIG.INT);
|
|
linux.sigaddset(&mask, posix.SIG.HUP);
|
|
|
|
posix.sigprocmask(posix.SIG.BLOCK, &mask, null);
|
|
|
|
const fd = try posix.signalfd(-1, &mask, linux.SFD.CLOEXEC);
|
|
|
|
return .{ .fd = fd };
|
|
}
|
|
|
|
pub fn deinit(self: SignalFd) void { _ = std.os.linux.close(self.fd); }
|
|
|
|
//
|
|
|
|
pub fn read(self: SignalFd) !Event
|
|
{
|
|
var info: linux.signalfd_siginfo = undefined;
|
|
|
|
_ = try posix.read(self.fd, std.mem.asBytes(&info));
|
|
|
|
return Event.fromSignal(@intCast(info.signo)) orelse .none;
|
|
}
|
|
};
|