1

Golang 优雅地关闭

 2 years ago
source link: https://blog.moonlightwatch.com/%E4%BB%A3%E7%A0%81%E7%AC%94%E8%AE%B0/2022/04/01/Golang%E4%BC%98%E9%9B%85%E5%9C%B0%E5%85%B3%E9%97%AD.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Golang 优雅地关闭

代码笔记 | 📅 2022-04-01 | golang

一般情况下,我们可以通过 Ctrl+C 关闭程序。一些情况下,我们需要对程序的关闭进行一些处理,此时我们可以这么做。

func main() {
// 一顿初始化操作
        quit := make(chan os.Signal, 1) // 创建一个 os.Signal 类型的 Channel
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) // 监听关闭信号,Ctrl+C 或者其他情况关闭进程都会触发
	<-quit // 收到关闭信号前挂起,收到信号后执行后面的代码
// 一顿关闭和清理操作
}

这样通过监听进程的关闭信号,来知晓程序何时关闭,进而对关闭前的程序进行处理。一般也就是:

  1. 关闭占用的资源(数据库,文件,端口啥的)
  2. 将下线通知发送到其他组件
  3. 写入关闭日志
  4. 等其他操作

那么,为啥不顺便监听 kill 信号(syscall.SIGKILL)呢?进程被kill的时候,进程是不会收到信号的……监听了也没用……


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK