douluan8828 2014-07-07 00:11
浏览 37
已采纳

设置流程退出代码的正确方法?

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?

  • 写回答

1条回答 默认 最新

  • dst67283 2014-07-07 00:45
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗