Skip to content

Instantly share code, notes, and snippets.

@lithdew
Last active October 8, 2020 11:10
Show Gist options
  • Save lithdew/cd2199d2fa08eb5cf220d3ea99568dc9 to your computer and use it in GitHub Desktop.
Save lithdew/cd2199d2fa08eb5cf220d3ea99568dc9 to your computer and use it in GitHub Desktop.
zig (windows): SetConsoleCtrlHandler() example
const std = @import("std");
const os = std.os;
const windows = os.windows;
pub const HANDLER_ROUTINE = fn(dwCtrlType: windows.DWORD) callconv(.Stdcall) windows.BOOL;
const funcs = struct {
extern "kernel32" fn SetConsoleCtrlHandler(HandlerRoutine: ?HANDLER_ROUTINE, Add: windows.BOOL) callconv(.Stdcall) windows.BOOL;
};
fn SetConsoleCtrlHandler(handler_routine: ?HANDLER_ROUTINE, add: bool) !void {
const success = funcs.SetConsoleCtrlHandler(handler_routine, if (add) windows.TRUE else windows.FALSE);
if (success == windows.FALSE) {
return switch (windows.kernel32.GetLastError()) {
else => |err| windows.unexpectedError(err)
};
}
}
pub const CTRL_C_EVENT: windows.DWORD = 0;
pub const CTRL_BREAK_EVENT: windows.DWORD = 1;
pub const CTRL_CLOSE_EVENT: windows.DWORD = 2;
pub const CTRL_LOGOFF_EVENT: windows.DWORD = 5;
pub const CTRL_SHUTDOWN_EVENT: windows.DWORD = 6;
var stopped = false;
fn handler(dwCtrlType: windows.DWORD) callconv(.Stdcall) windows.BOOL {
std.debug.print("Got console command: {}\n", .{dwCtrlType});
switch (dwCtrlType) {
CTRL_C_EVENT => {
@atomicStore(bool, &stopped, true, .SeqCst);
return windows.TRUE;
},
else => return windows.FALSE,
}
}
pub fn main() !void {
try SetConsoleCtrlHandler(handler, true);
while (!@atomicLoad(bool, &stopped, .SeqCst)) {
std.debug.print("Tick.\n", .{});
std.time.sleep(std.time.ns_per_ms * 500);
}
try SetConsoleCtrlHandler(handler, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment