如何处理SIGINT?
当我在程序中捕获 SIGINT 信号时,如何安全地清理资源? 在信号处理函数中,不可能调用 delete
运算符,因为我不知道如何释放使用 new
运算符创建的资源。
有什么想法吗?
When I catch SIGINT signal in my program, how can I safely clean up resources?
In signal handler function it is impossible to call delete
operator, because I don't know how to release resource created with new
operator.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的应用程序正在关闭,请不要担心内存。无论如何,一旦你终止,操作系统就会把它全部扔掉。
您需要在信号处理程序中清理的内容将比您的进程寿命更长 - 例如,如果您创建的子进程也需要退出,您应该告诉它这样做。
If your application is shutting down, don't worry about memory. The OS is going to throw it all away once you terminate anyway.
The things you need to clean up in your signal handler is stuff that's going to outlive your process otherwise - for example, if a child process you've created needs to exit also, you should tell it to do so.
一般来说,您不想在信号处理程序中做太多事情,除了设置一个布尔标志,该标志将由程序的其他部分做出反应,通常会导致一些循环失败并允许熟悉的方法有序关闭您在不涉及信号的情况下使用。使用此标志来协调关闭的原因是,某些库函数避免了在异步信号处理期间安全重新输入所需的妥协。即使某些使用线程特定内存的线程安全函数也可能无法应对异步重入。快速搜索发现了一些关于安全功能的讨论 http:// /book.chinaunix.net/special/ebook/addisonWesley/APUE2/0201433079/ch10lev1sec6.html#ch10lev1sec6。
Generally, you don't want to do much at all in your signal handler except set a boolean flag that will be reacted to by some other part of your program, typically causing some loops to fall through and allowing the familiar approach to orderly shutdown you'd use in cases not involving signals. The reason for using this flag to coordinate the shutdown is that some library functions eschew the compromises required to be safely reentered during async signal handling. Even some thread-safe functions using thread-specific memory may not cope with async reentry. A quick search found some discussion of safe functions at http://book.chinaunix.net/special/ebook/addisonWesley/APUE2/0201433079/ch10lev1sec6.html#ch10lev1sec6.