【问题标题】:Golang catch sigterm and continue applicationGolang 捕获 sigterm 并继续申请
【发布时间】:2019-11-06 04:06:33
【问题描述】:

是否可以在 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"

【问题讨论】:

  • 你的“无限”循环可以监控sigChan,一旦从它接收到值就会“中断”。这有什么问题?
  • 旁注:为您的信号制作一个上限为 1 的通道。
  • 该示例仅用于可视化,我无法控制无限循环,我正在尝试在内部库上实现它。

标签: go sigterm


【解决方案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
}

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多