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.

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

报告相同问题?

悬赏问题

  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题