我使用编写了一个简短的Go程序,os.Exit(2)并从Bash shell运行了该程序。
输入echo $?时,1无论传递到的退出值如何,它都会显示的值os.Exit。
的bash脚本下面示出了$?的值2一样的C程序。
为什么Go程序总是显示值1?如何使用除0或以外的代码退出1,并且应该使用此方法指示不同的退出状态?
package main
import "os"
func main() {
os.Exit(2)
}
Run Code Online (Sandbox Code Playgroud)
#!/bin/bash
exit 2
Run Code Online (Sandbox Code Playgroud)
#include <stdlib.h>
int main() {
exit(2);
}
Run Code Online (Sandbox Code Playgroud)
退出状态1,0不是您应用的退出状态,而是的退出状态go run。
如果您在使用运行你的应用程序go run,然后go run将返回0如果你的应用程序返回0退出状态,并且1如果您的应用程序返回一个非零状态(或go run本身出现故障)。
使用go build或构建您的应用程序go install,然后直接运行您的应用程序。然后,您将看到2退出状态。
运行的退出状态不是已编译二进制文件的退出状态。
注意:如果您在Go操场上运行您的应用程序,它还会指示您的应用程序的退出状态(无输出):
Program exited: status 2.
Run Code Online (Sandbox Code Playgroud)
此“问题”是在之前提出的,请参阅#13440。拉斯·考克斯(Russ Cox)的话:
The real question is whether 'go run x.go' is supposed to be just an interpreter for Go programs, like 'python x.py' or whether it is a tool that runs a subprocess and reports the results itself, like make. To date, the answer has been the latter. So it's not obvious the behavior is wrong, unless 'go run' is supposed to be some kind of interactive go command, which we've said in the past it is not.
And Dmitri Shuralyov's words:
An exit code is a single-dimensional value. When doing go run, there are 2 processes that run and 2 exit codes one may want to know.
However, go run is only able to report a single exit code value, not two. It's not possible to losslessly combine two exit codes into one. If it reported the exit code of the program it ran verbatim, then information about the go run exit code would be shadowed and effectively lost.
IMO, if one cares about the exact exit code of the program that is executed, they need to build it and execute it themselves. go run is a convenience feature for when your needs are not as demanding and you're okay with less information, because it's unable to communicate more information than it already does.
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |