Skip to content

Fix CTRL_CLOSE, CTRL_LOGOFF and CTRL_SHUTDOWN on windows #7122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 19, 2025
25 changes: 24 additions & 1 deletion tokio/src/signal/windows/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,21 @@ fn new(signum: u32) -> io::Result<RxFuture> {
Ok(RxFuture::new(rx))
}

fn event_requires_infinite_sleep_in_handler(signum: u32) -> bool {
// Returning from the handler function of those events immediately terminates the process.
// So for async systems, the easiest solution is to simply never return from
// the handler function.
//
// For more information, see:
// https://learn.microsoft.com/en-us/windows/console/handlerroutine#remarks
match signum {
console::CTRL_CLOSE_EVENT => true,
console::CTRL_LOGOFF_EVENT => true,
console::CTRL_SHUTDOWN_EVENT => true,
_ => false,
}
}

#[derive(Debug)]
pub(crate) struct OsStorage {
ctrl_break: EventInfo,
Expand Down Expand Up @@ -114,7 +129,15 @@ unsafe extern "system" fn handler(ty: u32) -> BOOL {
// the handler routine is always invoked in a new thread, thus we don't
// have the same restrictions as in Unix signal handlers, meaning we can
// go ahead and perform the broadcast here.
if globals.broadcast() {
let event_was_handled = globals.broadcast();

if event_requires_infinite_sleep_in_handler(ty) {
loop {
std::thread::sleep(std::time::Duration::MAX);
}
}

if event_was_handled {
1
} else {
// No one is listening for this notification any more
Expand Down
Loading