英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论