英文:
Correct way to set Exit Code of Process?
问题
在Go语言中,设置进程的退出码的正确方式是使用os.Exit(code int)
函数。这个函数会立即终止进程,并且不会执行任何延迟函数。另外,你也可以使用panic
函数来退出进程并设置非零的状态码,尽管这会在控制台上输出堆栈跟踪信息。总的来说,使用os.Exit
函数是设置退出码的正确方式。
英文:
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
得分: 20
将os.Exit
作为最后一个延迟执行的函数。延迟函数在包围的函数返回之前立即执行,按照它们被延迟的相反顺序执行。例如,
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
}
输出:
Hello, 世界
Another deferred func
[进程以非零状态退出]
Go Playground:
http://play.golang.org/p/o0LfisANwb
"defer"语句会调用一个函数,在包围的函数返回时延迟执行,无论是因为包围的函数执行了返回语句,到达了函数体的末尾,还是因为相应的goroutine正在发生恐慌。
DeferStmt = "defer" Expression .
表达式必须是一个函数或方法调用;不能加括号。内置函数的调用受限制,就像表达式语句一样。
每次"defer"语句执行时,函数值和调用的参数会像平常一样被求值并重新保存,但实际的函数体不会被执行。相反,延迟函数会在包围的函数返回之前立即执行,按照它们被延迟的相反顺序执行。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论