local-host 2012-06-29 21:05 采纳率: 100%
浏览 213
已采纳

是否有可能捕捉 Ctrl + c 信号并以"defer"的方式运行一个清理函数?

I want to capture the <kbd>Ctrl+C</kbd> (SIGINT) signal sent from the console and print out some partial run totals.

Is this possible in Golang?

Note: When I first posted the question I was confused about <kbd>Ctrl+C</kbd> being SIGTERM instead of SIGINT.

转载于:https://stackoverflow.com/questions/11268943/is-it-possible-to-capture-a-ctrlc-signal-and-run-a-cleanup-function-in-a-defe

  • 写回答

9条回答 默认 最新

  • 喵-见缝插针 2012-06-29 21:16
    关注

    You can use the os/signal package to handle incoming signals. ^C is SIGINT, so you can use this to trap os.Interrupt.

    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    go func(){
        for sig := range c {
            // sig is a ^C, handle it
        }
    }()
    

    The manner in which you cause your program to terminate and print information is entirely up to you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作