如何退出执行延迟呼叫的go程序? [英] How to exit a go program honoring deferred calls?
问题描述
我需要使用 defer
释放使用 C
库手动创建的分配,但是我还需要 os.Exit
有时处于非零状态。棘手的部分是 os.Exit
跳过任何延迟的指令:
I need to use defer
to free allocations manually created using C
library, but I also need to os.Exit
with non 0 status at some point. The tricky part is that os.Exit
skips any deferred instruction:
package main
import "fmt"
import "os"
func main() {
// `defer`s will _not_ be run when using `os.Exit`, so
// this `fmt.Println` will never be called.
defer fmt.Println("!")
// sometimes ones might use defer to do critical operations
// like close a database, remove a lock or free memory
// Exit with status code.
os.Exit(3)
}
游乐场:http://play.golang.org/p/CDiAh9SXRM > https://gobyexample.com/exit
Playground: http://play.golang.org/p/CDiAh9SXRM stolen from https://gobyexample.com/exit
因此,如何退出执行程序以兑现声明为 defer
电话? os.Exit
是否有其他选择?
So how to exit a go program honoring declared defer
calls? Is there any alternative to os.Exit
?
推荐答案
runtime.Goexit()
是简单的方法
runtime.Goexit()
is the easy way to accomplish that.
Goexit终止调用它的goroutine。没有其他goroutine受到影响。 Goexit在终止goroutine之前会运行所有延迟的调用。但是,由于Goexit并不慌张,因此这些延迟函数中的任何恢复调用都将返回nil。
Goexit terminates the goroutine that calls it. No other goroutine is affected. Goexit runs all deferred calls before terminating the goroutine. Because Goexit is not panic, however, any recover calls in those deferred functions will return nil.
但是:
从主goroutine调用Goexit会终止该goroutine,而不会返回func main。由于func main尚未返回,因此程序将继续执行其他goroutine。如果所有其他goroutine都退出,则程序将崩溃。
Calling Goexit from the main goroutine terminates that goroutine without func main returning. Since func main has not returned, the program continues execution of other goroutines. If all other goroutines exit, the program crashes.
因此,如果您从主goroutine调用它,则在<$ c的顶部$ c> main 您需要添加
So if you call it from the main goroutine, at the top of main
you need to add
defer os.Exit(0)
下面,您可能希望添加其他一些 defer
语句,通知其他goroutine停止并清理。
Below that you might want to add some other defer
statements that inform the other goroutines to stop and clean up.
这篇关于如何退出执行延迟呼叫的go程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!