正确设置进程退出码的方法? [英] Correct way to set Exit Code of Process?

查看:116
本文介绍了正确设置进程退出码的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试着改变main func为

  func main()int {
return -1
}

但是这会导致错误 func main必须没有参数并且没有返回值



好,所以有 os.Exit(code int),但是这会立即中止进程并且不会干净地退出(例如,没有延迟运行) p>

我还发现 panic 会退出进程并将状态码设置为非零,这可能是最好的方式,尽管它转储堆栈跟踪到控制台。



设置退出代码的正确方法是什么?

解决方案

使 os.Exit 执行最后一个延迟函数。延迟函数在周围函数返回之前立即执行,按照推迟的顺序执行。例如,

 包主

导入(
fmt
os


func main(){
code:= 0
defer func(){
os.Exit(code)
$()
推迟func(){
fmt.Println(另一个延期函数)
}()
fmt.Println(Hello,世界)
code = 1
}

输出:

 您好,世界
另一个延期函数
[进程退出时为非零状态]



Go Playground:



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


Go编程语言规范



推迟语句



延迟语句调用功能wh因为
环绕函数执行了return语句,达到了
其函数体的结尾,或者因为相应的goroutine是$ b,所以执行被推迟到
$ b恐慌。

DeferStmt =defer表达式。

表达式必须是函数或方法调用;它不能被
括起来。对于
表达式语句,内置函数的调用是受到限制的。



每次执行defer语句时,函数值和
参数对通话进行评估,并重新保存,但不执行
实际功能体。相反,延迟函数是
在周围函数返回之前立即执行的,它们是以
相反顺序被延迟的。



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?

解决方案

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.

这篇关于正确设置进程退出码的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆