title: How to exit a go program honoring deferred calls?
body: <p>I need to use <code>defer</code> to free allocations manually created using <code>C</code> library, but I also need to <code>os.Exit</code> with non 0 status at some point. The tricky part is that <code>os.Exit</code> skips any deferred instruction:</p>
  
  <pre><code>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)
  }
  </code></pre>
  
  <p>Playground: <a href="http://play.golang.org/p/CDiAh9SXRM">http://play.golang.org/p/CDiAh9SXRM</a> stolen from <a href="https://gobyexample.com/exit">https://gobyexample.com/exit</a></p>
  
  <p>So how to exit a go program honoring declared <code>defer</code> calls? Is there any alternative to <code>os.Exit</code>?</p>