How to handle SIGUSR1 and SIGUSR2

So far I cant find anything about signal handling in zig, and I need my program to be able to respond to SIGUSR signals being sent. Please help.

1 Like

Hello @jackedak

Using std.posix.sigaction you can register a signal handler.

Example:

const std = @import("std");

fn usrHandler(sig: i32) callconv(.C) void {
    if (sig == std.posix.SIG.USR1) {
        // ...
    }
}

pub fn main() !void {
    var sa: std.posix.Sigaction = .{
        .handler = .{ .handler = usrHandler },
        .mask = std.posix.empty_sigset,
        .flags = std.posix.SA.RESTART,
    };
    try std.posix.sigaction(std.posix.SIG.USR1, &sa, null);
    try std.posix.sigaction(std.posix.SIG.USR2, &sa, null);
}

Welcome to ziggit :slight_smile:

3 Likes

Thank you so much, however is there any way to get the PID of the process that sent the signal, if that’s even possible?

1 Like

Yes, it is possible.

Use the sigaction variant of the handler (that receives three parameters). The second parameter (siginfo_t) have the pid and uid of the sender process.

Example:

const std = @import("std");

fn usrHandler(sig: i32, info: *const std.posix.siginfo_t, _: ?*anyopaque) callconv(.C) void {
    if (sig == std.posix.SIG.USR1) {
        const pid = info.fields.common.first.piduid.pid;
        // ... use pid
    }
}

pub fn main() !void {
    var sa: std.posix.Sigaction = .{
        .handler = .{ .sigaction = usrHandler },
        .mask = std.posix.empty_sigset,
        .flags = std.posix.SA.RESTART,
    };
    try std.posix.sigaction(std.posix.SIG.USR1, &sa, null);
    try std.posix.sigaction(std.posix.SIG.USR2, &sa, null);
}
4 Likes