在退出时调用API吗?

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

Call API at Exit?

问题

我正在使用一个具有'bind'函数的API,在我的程序开始时调用它,但为了成为一个好的API用户,我需要在程序退出时调用'unbind'函数,无论出于何种原因。有没有办法做到这一点?我在Google上找不到任何信息,而且"defer api.Unbind()"似乎没有被调用。谢谢。

英文:

I'm using an API that has a 'bind' function that I call at the start of my program, but to be a good API user, I need to call the 'unbind' function when my program quits for any reason. Is there a way to do that? I can't find anything on Google, and defer api.Unbind() doesn't seem to get called. Thx.

答案1

得分: 1

没有一种方法可以百分之百地保证在异常程序终止之前调用某些代码。你能做到的最接近的方式是对os.Interrupt(以及Unix系统上的syscall.SIGTERM)做出反应,并确保在此之后完成清理工作。实现这一点的一个好方法是使用NotifyContext,因为它与context包很好地结合在一起,主要用于实现(可能)长时间运行的代码的取消。

英文:

There is no single way to get a 100% guarantee that some code is called before abnormal program termination. The closest you can get is to react to os.Interrupt (and also syscall.SIGTERM on Unix systems) and make sure your cleanup is done thereafter. A good way to achieve this is to use NotifyContext because it ties in nicely with the context package the main use of which is to allow for implementing cancellation of (potentially) long-running code.

huangapple
  • 本文由 发表于 2021年11月5日 02:02:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/69843822.html
匿名

发表评论

匿名网友

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

确定