Golang抓住sigterm并继续申请

时间:2019-06-24 10:53:47

标签: go sigterm

是否有可能在Golang中捕获sigterm并继续执行代码,如恐慌/推迟?

示例:

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

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

// "app started"
// CTRL + C
// ^C "got interrupt signal:  interrupt"
// "infinite loop stopped and got here"

1 个答案:

答案 0 :(得分:1)

这很容易实现。由于信号通道需要阻塞并等待信号,因此您必须在其他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 SIGTERM %v", sig)
    // shutdown other goroutines gracefully
    // close other resources
}