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

后端 未结 10 1152
抹茶落季
抹茶落季 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 15:48

    You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

    I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

    https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

    You can do this in a 'defer' fashion.

    example for shutting down a server gracefully :

    srv := &http.Server{}
    
    go_shutdown_hook.ADD(func() {
        log.Println("shutting down server")
        srv.Shutdown(nil)
        log.Println("shutting down server-done")
    })
    
    l, err := net.Listen("tcp", ":3090")
    
    log.Println(srv.Serve(l))
    
    go_shutdown_hook.Wait()
    

提交回复
热议问题