Exit status without os.Exit

1,973 views
Skip to first unread message

Tobias Matt

unread,
Aug 7, 2011, 5:36:49 PM8/7/11
to golang-nuts
Today I learned, that defer don't work with os.Exit, but how can I
return an exit status without os.Exit?

Evan Shaw

unread,
Aug 7, 2011, 5:39:57 PM8/7/11
to Tobias Matt, golang-nuts
On Mon, Aug 8, 2011 at 9:36 AM, Tobias Matt <t.ma...@gmail.com> wrote:
> Today I learned, that defer don't work with os.Exit, but how can I
> return an exit status without os.Exit?

Defer doesn't work with os.Exit, but it's easy to work around;

package main

import (
"fmt"
"os"
)

func main() {
os.Exit(realMain())
}

func realMain() int {
defer fmt.Println("hi")
return 1
}

- Evan

Paul Borman

unread,
Aug 7, 2011, 5:46:25 PM8/7/11
to Evan Shaw, Tobias Matt, golang-nuts
It is more complicated than that when you have more than a single goroutine.  This solution also does not allow exiting the program anyplace but from realMain.  If you are single threaded you can implement an exit using panic and a deferred recover, but that will not help if you have multiple goroutines.  os.Exit doesn't unwind anything, panic unwinds the stack it is on.  I have brought this up on the dev mailing list.  I think having the ability to exit a program and have all stacks unwound and defers called would require a language change.

    -Paul

Julien Laffaye

unread,
Aug 7, 2011, 5:53:09 PM8/7/11
to golan...@googlegroups.com
On 08/07/2011 23:46, Paul Borman wrote:
> It is more complicated than that when you have more than a single
> goroutine. This solution also does not allow exiting the program
> anyplace but from realMain. If you are single threaded you can
> implement an exit using panic and a deferred recover, but that will
> not help if you have multiple goroutines. os.Exit doesn't unwind
> anything, panic unwinds the stack it is on. I have brought this up on
> the dev mailing list. I think having the ability to exit a program
> and have all stacks unwound and defers called would require a language
> change.
You want something like atexit(3).
Maybe it could be implemented with os.signal and a slice of functions to
run when the process is about to exit.

jimmy frasche

unread,
Aug 7, 2011, 6:00:56 PM8/7/11
to Julien Laffaye, golan...@googlegroups.com
os.Exit(<-exit_code)

Russ Cox

unread,
Aug 8, 2011, 8:07:01 AM8/8/11
to jimmy frasche, Julien Laffaye, golan...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages