在Go中,当成功终止应用程序时,是否需要使用`os.Exit(0)`呢?

huangapple go评论80阅读模式
英文:

Do I need to use os.Exit(0) when succefully terminanting an application in Go?

问题

我最近发现了Go标准库中的os.Exit函数,并且在一些教程中也见过它。

由于Go的func main()函数不返回任何值,所以在main()函数中使用return而不是os.Exit(0)是否有关系呢?

我知道os.Exit还会忽略Go代码中的defer语句,但在这种情况下,我只想知道对于操作系统来说,returnos.Exit(0)之间是否没有区别。

英文:

I`ve recently discovered the os.Exit function on Go standard library, and I`ve seen it in some tutorials as well.

Since the Go`s func main() does not return any value, does it matter if I simply use return in the main() function isteand of os.Exit(0)?

I know os.Exit also ignores defers in Go code, but in this case I just want to know if there`s no difference for the OS between return and os.Exit(0).

答案1

得分: 4

你描述的区别是正确的,os.Exit(0)会立即结束程序,忽略任何延迟执行的操作。使用return语句,程序将以默认的代码0结束。

在defer语句之外,基本上没有区别。

英文:

the difference you described is correct, os.Exit(0) finishes the program immediately, ignoring any defers. With return your program will finish with default code 0.

test-exit$ cat main.go
> package main
> 
> func main() {
> 	return
> }
test-exit$ go run main.go
test-exit$ echo $? // shows status code of last executed command
> 0

So outside the defer case there is basically no difference.

huangapple
  • 本文由 发表于 2022年8月4日 21:52:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73237149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定