defer and os.Exit

888 views
Skip to first unread message

Jeff R. Allen

unread,
Nov 9, 2010, 8:50:05 AM11/9/10
to golang-nuts
Just a short note to fellow Go newbies who know about defer and know
about os.Exit() (or log.Exit()) but have never thought about the
implications of mixing them in the same function.

os.Exit calls the underlying system call exit, and after that, there's
NO possibility the Go runtime can do any more work; it does not exist
any more, except as so much digital garbage in the kernel's page
cache.

If you want your defers to fire, you have to exit the subroutine
either via panic() or via return.

Just got bit by that, and so I thought I would mention it here. I'm
trying to think if the docs could have saved me from this mistake, but
it seems like it's just something you have to remember about defer:
it's not magic, and once the process is dead, no defers happen.

Sorry this is obvious, but that's the nature of newbie errors...

-jeff

bflm

unread,
Nov 9, 2010, 9:05:13 AM11/9/10
to golang-nuts
On Nov 9, 2:50 pm, "Jeff R. Allen" <j...@nella.org> wrote:
> Just got bit by that, and so I thought I would mention it here. I'm
> trying to think if the docs could have saved me from this mistake, but
> it seems like it's just something you have to remember about defer:
> it's not magic, and once the process is dead, no defers happen.
It's precisely documented:

http://localhost:6060/doc/go_spec.html#Handling_panics

"When a function F calls panic, normal execution of F stops
immediately. Any functions whose execution was deferred by the
invocation of F are run in the usual way, and then F returns to its
caller. ..."

Calling os.Exit is not a panic call, so the defer guarantee above
doesn't apply.
Reply all
Reply to author
Forward
0 new messages