Golang捕获sigterm并继续应用

Cae*_*chi 7 signals go sigterm

是否有可能在 Golang 中捕获 asigterm并继续执行代码,就像恐慌/延迟一样?

例子:

func main() {
    fmt.Println("app started")
    setupGracefulShutdown()

    for {
    }
    close()    
}

func close() {
    fmt.Println("infinite loop stopped and got here")
}

func setupGracefulShutdown() {
    sigChan := make(chan os.Signal)
    signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)

    go func() {
        fmt.Println(" got interrupt signal: ", <-sigChan)
    }()
}

// "app started"
// CTRL + C
// ^C "got interrupt signal:  interrupt"
// app don't stop
Run Code Online (Sandbox Code Playgroud)

我想要的是打印infinite loop stopped and got here并完成申请。

// "app started"
// CTRL + C
// ^C "got interrupt signal:  interrupt"
// "infinite loop stopped and got here"
Run Code Online (Sandbox Code Playgroud)

geo*_*eok 12

这很容易实现。由于信号通道需要阻塞并等待信号,因此您必须在不同的 goroutine 中启动业务逻辑代码。

func main() {
    cancelChan := make(chan os.Signal, 1)
    // catch SIGETRM or SIGINTERRUPT
    signal.Notify(cancelChan, syscall.SIGTERM, syscall.SIGINT)
    go func() {
        // start your software here. Maybe your need to replace the for loop with other code
        for {
            // replace the time.Sleep with your code
            log.Println("Loop tick")
            time.Sleep(time.Second)
        }
    }()
    sig := <-cancelChan
    log.Printf("Caught signal %v", sig)
    // shutdown other goroutines gracefully
    // close other resources
}
Run Code Online (Sandbox Code Playgroud)