英文:
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() {
<-sigChan
fmt.Println("save to disk and clean")
}()
sig := <-sigChan
log.Println("reliable termination", sig)
s.Shutdown(tc)
答案1
得分: 1
Docker在停止容器时会发送SIGTERM和SIGKILL信号。如果你的代码已经注册了这些信号,那么应该能够接收到它们。
如果仍然无法接收到信号,请检查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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论