如何退出对延迟调用表示尊重的 Go 程序?

我需要使用 defer来释放使用 C库手动创建的分配,但是我也需要在某些时候使用非0状态的 os.Exit。棘手的是,os.Exit会跳过任何延迟的指令:

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/CDiAh9SXRMhttps://gobyexample.com/exit被盗

那么,如何退出一个去荣誉程序声明 defer呼叫? 有没有任何替代 os.Exit

33503 次浏览

Just move your program down a level and return your exit code:

package main


import "fmt"
import "os"


func doTheStuff() int {
defer fmt.Println("!")


return 3
}


func main() {
os.Exit(doTheStuff())
}

After some research, refer to this this, I found an alternative that:

We can take advantage of panic and recover. It turns out that panic, by nature, will honor defer calls but will also always exit with non 0 status code and dump a stack trace. The trick is that we can override last aspect of panic behavior with:

package main


import "fmt"
import "os"


type Exit struct{ Code int }


// exit code handler
func handleExit() {
if e := recover(); e != nil {
if exit, ok := e.(Exit); ok == true {
os.Exit(exit.Code)
}
panic(e) // not an Exit, bubble up
}
}

Now, to exit a program at any point and still preserve any declared defer instruction we just need to emit an Exit type:

func main() {
defer handleExit() // plug the exit handler
defer fmt.Println("cleaning...")
panic(Exit{3}) // 3 is the exit code
}

It doesn't require any refactoring apart from plugging a line inside func main:

func main() {
defer handleExit()
// ready to go
}

This scales pretty well with larger code bases so I'll leave it available for scrutinization. Hope it helps.

Playground: http://play.golang.org/p/4tyWwhcX0-

runtime.Goexit() is the easy way to accomplish that.

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.

However:

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.

So if you call it from the main goroutine, at the top of main you need to add

defer os.Exit(0)

Below that you might want to add some other defer statements that inform the other goroutines to stop and clean up.

For posterity, for me this was a more elegant solution:

func main() {
retcode := 0
defer func() { os.Exit(retcode) }()
defer defer1()
defer defer2()


[...]


if err != nil {
retcode = 1
return
}
}