You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Go语言信号处理器在Windows系统正常工作?

问题原因

Windows与Linux的信号处理机制存在差异,你当前代码中仅监听syscall.SIGINT,无法在Windows系统上正确捕获Ctrl+C触发的中断信号。

解决方案

使用Go标准库提供的跨平台中断信号标识os.Interrupt,它会自动适配不同操作系统的对应信号。若需要支持Windows上的Ctrl+Break触发的中断,可额外添加syscall.SIGBREAK到监听列表。

修改后的完整代码:

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    detectShutdown()
    fmt.Println("Running")
    time.Sleep(5 * time.Second)
}

func detectShutdown() {
    sigChan := make(chan os.Signal, 1)
    // 监听跨平台中断、终止及Windows特有的Break信号
    signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM, syscall.SIGBREAK)
    go func() {
        sig := <-sigChan
        fmt.Printf("Signal [%s] detected\n", sig)
        os.Exit(1)
    }()
}
测试效果

Windows下按Ctrl+C,程序会输出:

Running
^CSignal [interrupt] detected

内容的提问来源于stack exchange,提问作者user4586864

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 14:15:37