On my system, the following code (written in Zig, using zigwin32 for bindings to the WinAPI) returns the error code 58 after the spawned console is closed:
const std = @import("std");
const win32 = @import("zigwin32/win32.zig");
const foundation = win32.foundation;
const console = win32.system.console;
// Overrides default behvior, including CTRL_CLOSE_EVENT
fn consoleHandler(_: u32) callconv(.C) foundation.BOOL {
return 1;
}
pub fn wWinMain(_: foundation.HINSTANCE, _: ?foundation.HINSTANCE, _: [*c]const u16, _: c_int) c_int {
std.debug.assert(console.AllocConsole() != 0);
std.debug.assert(console.SetConsoleCtrlHandler(consoleHandler, 1) != 0);
while (true) {}
return 0;
}
Can someone please explain to me why this is happening?
In my mind the program should never stop because there is no explicit ExitProcess call and the while loop is never exited from. The only way the program can end, I think, is if the console's events run on a separate thread and close the main thread, returning 58, but I'm not sure why or how this is happening.
Not by you, no. But there is one, actually. It is being called by the OS.
That is exactly what happens. Per the HandlerRoutine callback function documentation:
When a console window is closed, it's list of handlers are called for CTRL_CLOSE_EVENT, and if any return TRUE (as yours does), the process is terminated immediately.
So, a console handler can't stop its process from being terminated, it can only control whether subsequent handlers are called or not.