Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to set Exit Code of Process?

Tags:

go

In Go what is the proper way to set the exit code of the process?

I tried changing main func to

func main() int {
    return -1
}

But this causes error func main must have no arguments and no return values

OK so there is os.Exit(code int), however this immediately aborts the process and does not exit cleanly (no deferreds are run for example).

I also found that panic will exit process and set status code to nonzero, this may be the best way, although it dumps a stack trace to console.

What is the right way to set the exit code?

like image 696
Greg Ennis Avatar asked Jul 07 '14 00:07

Greg Ennis


1 Answers

Make os.Exit the last deferred function executed. Deferred functions are executed immediately before the surrounding function returns, in the reverse order they were deferred. For example,

package main

import (
    "fmt"
    "os"
)

func main() {
    code := 0
    defer func() {
        os.Exit(code)
    }()
    defer func() {
        fmt.Println("Another deferred func")
    }()
    fmt.Println("Hello, 世界")
    code = 1
}

Output:

Hello, 世界
Another deferred func
 [process exited with non-zero status]

Go Playground:

http://play.golang.org/p/o0LfisANwb

The Go Programming Language Specification

Defer statements

A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

DeferStmt = "defer" Expression .

The expression must be a function or method call; it cannot be parenthesized. Calls of built-in functions are restricted as for expression statements.

Each time the "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function body is not executed. Instead, deferred functions are executed immediately before the surrounding function returns, in the reverse order they were deferred.

like image 98
peterSO Avatar answered Oct 16 '22 03:10

peterSO