如何在退出时调用函数

huangapple go评论156阅读模式
英文:

How to call function on exit

问题

我正在使用Docker来运行我的Go项目,我想在退出或终止时调用一个函数,但是函数内部的内容没有打印出来:

以下是我目前在主函数中的代码:

sigChan := make(chan os.Signal)
signal.Notify(sigChan, os.Interrupt)
signal.Notify(sigChan, os.Kill)
defer func() {
    <-sigChan
    fmt.Println("save to disk and clean")
}()
sig := <-sigChan
log.Println("reliable termination", sig)

s.Shutdown(tc)

请注意,这是一个代码示例,我只翻译了其中的注释和字符串。

英文:

I am running my go project using docker for containers and I would like to call a function when it exits or kill, but what's within the function is not printing:

here is the code I currently have in the main function:

sigChan := make(chan os.Signal)
	signal.Notify(sigChan, os.Interrupt)
	signal.Notify(sigChan, os.Kill)
	defer func() {
        &lt;-sigChan
        fmt.Println(&quot;save to disk and clean&quot;)
    }()
	sig := &lt;-sigChan
	log.Println(&quot;reliable termination&quot;, sig)

	s.Shutdown(tc) 

答案1

得分: 1

Docker在停止容器时会发送SIGTERMSIGKILL信号。如果你的代码已经注册了这些信号,那么应该能够接收到它们。

如果仍然无法接收到信号,请检查entrypoint是否使用了shell形式,因为shell形式不会传递信号,请将其改为exec形式

> shell形式会阻止使用任何CMD或run命令行参数,但它的缺点是你的ENTRYPOINT将作为/bin/sh -c的子命令启动,而/bin/sh -c不会传递信号。

英文:

Docker sends SIGTERM and SIGKILL to container on stop command. Your code should receive these if registered for.

If not receiving still, check if entrypoint is shell form because shell form does not pass the signals, change it to exec form

> The shell form prevents any CMD or run command line arguments from
> being used, but has the disadvantage that your ENTRYPOINT will be
> started as a subcommand of /bin/sh -c, which does not pass signals

huangapple
  • 本文由 发表于 2022年8月27日 08:10:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/73507516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定