Is it possible to capture a Ctrl+C signal and run a cleanup function, in a “defer” fashion?

后端 未结 10 1138
抹茶落季
抹茶落季 2020-11-29 15:30

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

Is this possible in Golang?

10条回答
  •  再見小時候
    2020-11-29 16:14

    There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.

    // capture ctrl+c and stop CPU profiler                            
    c := make(chan os.Signal, 1)                                       
    signal.Notify(c, os.Interrupt)                                     
    go func() {                                                        
      for sig := range c {                                             
        log.Printf("captured %v, stopping profiler and exiting..", sig)
        pprof.StopCPUProfile()                                         
        os.Exit(1)                                                     
      }                                                                
    }()    
    

提交回复
热议问题