go - 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"
解决方案
这很容易实现。因为信号通道需要阻塞和等待信号,所以你必须在不同的 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
}
推荐阅读
- python - pytest 可以在测试类中运行测试吗?
- android - 最新的 android studio 屏幕截图失败
- angular - TypeScript - 更新到 Angular 7 后 WebStorm 中的初始化错误
- c# - 如何在使用 MOQ 进行模拟时将 Lazy 的类对象类型传递给构造函数
- php - 子目录中的自定义链接('/')重定向到主目录
- php - 在php中用数字和字母实现计数器
- angular - Angular 6 无法获取在显示来自 ngFor 循环数据的数据的输入中键入的新值
- ssl - 运行 Google Cloud Datalab 笔记本时出现 cffi.error.VerificationError(未定义符号:SSLv2_client_method)
- android - 如何为 PIP 功能设置视频 URL 而不是本地视频资源?
- c++ - 从文件中读取直接访问 C++