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

后端 未结 10 1133
抹茶落季
抹茶落季 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:01

    This works:

    package main
    
    import (
        "fmt"
        "os"
        "os/signal"
        "syscall"
        "time" // or "runtime"
    )
    
    func cleanup() {
        fmt.Println("cleanup")
    }
    
    func main() {
        c := make(chan os.Signal)
        signal.Notify(c, os.Interrupt, syscall.SIGTERM)
        go func() {
            <-c
            cleanup()
            os.Exit(1)
        }()
    
        for {
            fmt.Println("sleeping...")
            time.Sleep(10 * time.Second) // or runtime.Gosched() or similar per @misterbee
        }
    }
    

提交回复
热议问题