goexitdefer-keyword

How to exit a go program honoring deferred calls?


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?


Solution

  • 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.