How to exit a go program honoring deferred calls?

前端 未结 4 422
执笔经年
执笔经年 2021-01-30 04:10

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

4条回答
  •  Happy的楠姐
    2021-01-30 04:32

    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.

提交回复
热议问题