100

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?

marcio
  • 10,002
  • 11
  • 54
  • 83
  • http://stackoverflow.com/questions/24601516/correct-way-to-set-exit-code-of-process – Chris Cherry Dec 23 '14 at 23:29
  • @ctcherry no success with defer `os.Exit`: http://play.golang.org/p/IsSI9VB7j8 – marcio Dec 23 '14 at 23:39
  • reverse the defer order http://play.golang.org/p/a4RP5BiXbc – Chris Cherry Dec 23 '14 at 23:41
  • oh I see, that's a problem. In my case I can only defer `os.Exit` after running other operations that also defer something... let me think a little more. – marcio Dec 23 '14 at 23:44
  • `defer` in `main` combined with `os.Exit` is definitely a rough spot. Architecting around it like @Rob Napier does below is a better way to go. – Chris Cherry Dec 23 '14 at 23:47
  • Is this a suitable strategy? http://soniacodes.wordpress.com/2011/04/28/deferred-functions-and-an-exit-code/ At least it doesn't seem to force a code pattern. – marcio Dec 24 '14 at 00:14
  • `panic` is an exception, I don't think running defers and passing and error code should require that kind of maneuver. Keeping the defer out of main seems like a simpler and more idiomatic approach. – Chris Cherry Dec 24 '14 at 00:35
  • @ctcherry I ended up creating a response but thanks for the warning. I'll keep this in mind :) – marcio Dec 24 '14 at 00:52

4 Answers4

57

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())
}
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • 1
    So I shouldn't to use `defer` inside `func main` or any function that exits? – marcio Dec 23 '14 at 23:32
  • 6
    More to the point, I don't recommend using `os.Exit()` in random places in the code. It makes testing very difficult besides the problem of error codes. peterSO's solution that @ctcherry links is ok, but it doesn't scale well IMO to a larger program. You'd have to make the `code` global. I believe you should keep main() fairly simple, and have it just take care of the OS-level things (like the final status code). – Rob Napier Dec 23 '14 at 23:37
  • Hi, I found a way to handle this without impose any architecture. Anyway, +1 because it's a good advice to always try KISS first. – marcio Dec 24 '14 at 00:59
40

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.

EMBLEM
  • 2,207
  • 4
  • 24
  • 32
  • 2
    I had no idea `runtime.Goexit()` existed. Is this from some recent release? – marcio Sep 29 '16 at 04:52
  • 3
    @marcio I did some digging in the Go repositories. I couldn't find exactly when it was introduced, but I did find [this test that references it and is "Copyright 2013"](https://github.com/golang/go/blob/53fd522c0db58f3bd75d85295f46bb06e8ab1a9b/test/fixedbugs/issue5963.go) from before you posted this question. – EMBLEM Sep 29 '16 at 06:22
  • 3
    @marcio I did a little more digging and found [an archive of the documentation from 2009](http://web.archive.org/web/20091215044631/http://golang.org/pkg/runtime). Goexit is listed there. – EMBLEM Oct 11 '16 at 21:18
  • 1
    I'm gonna mark this as the accepted answer. The other answers are definitely still valid, but this seems the simplest approach - for now :D – marcio Oct 11 '16 at 23:35
34

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-

Community
  • 1
  • 1
marcio
  • 10,002
  • 11
  • 54
  • 83
  • Best answer of the all so far! One question, how to deal with normal exit then? How to make sure the `handleExit` get called even with normal exit ? Ref: https://play.golang.org/p/QDJum4kOXk un-comment the `//panic` and see the difference. – xpt Jan 06 '17 at 22:12
  • I think a handle for a normal exit 0 event doesn't exist, but you can always panic(Exit{0}) and then handle it or maybe defer handleNormalExit() before anything else on main()? – marcio Jan 18 '17 at 19:56
  • Yes, this sounds more like the exceptions bubbling in java/C# – Macindows Jul 11 '21 at 14:12
29

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
    }
}
  • 2
    This really takes the best parts of the other answers. – PRMan Apr 29 '20 at 18:20
  • I was breaking my head exploring different ways around this issue; why os.exit does not also call the "defer" functions but in my case simply using "return" instead of os.exit solved the issue. Now I feel stupid I didnt think of it earlier – Macindows Jul 11 '21 at 14:04
  • on a side note, does defer1, defer2 execute in chronological order? – Macindows Jul 11 '21 at 14:05
  • 1
    @Macindows This is Go standard: last to first. So `defer2()`, then `defer1()` – Mike Gleason jr Couturier Jul 14 '21 at 13:06
  • 1
    This code will suppress panics. Also, if `retcode` is not changed (during a panic, for example), it will return always 0 (no erro). If you are sure your code is panic free, you are probably fine with that, though – rubens21 Feb 09 '22 at 15:50