首页 > 解决方案 > Golang 捕获 sigterm 并继续申请

问题描述

是否可以sigterm在 Golang 中捕获 a 并继续编写代码,例如恐慌/延迟?

例子:

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"

标签: gosigterm

解决方案


这很容易实现。因为信号通道需要阻塞和等待信号,所以你必须在不同的 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
}

推荐阅读