Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a go program honoring deferred calls?

Tags:

go

exit

deferred

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) } 

Playground: http://play.golang.org/p/CDiAh9SXRM stolen from https://gobyexample.com/exit

So how to exit a go program honoring declared defer calls? Is there any alternative to os.Exit?

like image 498
marcio Avatar asked Dec 23 '14 23:12

marcio


2 Answers

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()) } 
like image 189
Rob Napier Avatar answered Sep 19 '22 12:09

Rob Napier


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.

like image 31
EMBLEM Avatar answered Sep 19 '22 12:09

EMBLEM