gpt4 book ai didi

Go os.Exit(2) 显示一个 bash $?值为 1

转载 作者:IT王子 更新时间:2023-10-29 01:18:55 26 4
gpt4 key购买 nike

我使用 os.Exit(2) 编写了一个简短的 Go 程序并从 Bash shell 运行它。

当我键入 echo $? 时,无论传递给 os.Exit 的退出值如何,它都会显示值 1

下面的 Bash 脚本显示 $? 的值为 2,C 程序也是如此。

为什么 Go 程序总是显示值 1?如何使用 01 以外的代码退出,我是否应该使用此方法来指示不同的退出状态?

package main

import "os"

func main() {
os.Exit(2)
}
#!/bin/bash

exit 2
#include <stdlib.h>

int main() {
exit(2);
}

最佳答案

退出状态 10 不是您应用的退出状态,而是 go run 的退出状态。

如果您使用 go run 运行您的应用程序,那么当您的应用程序返回 0 时,go run 将返回 0 > 退出状态,如果您的应用返回非零状态(或 go run 本身失败),则为 1

使用 go buildgo install 构建您的应用,然后直接运行您的应用。然后您将看到 2 退出状态。

引自Command go: Compile and run Go program:

The exit status of Run is not the exit status of the compiled binary.

注意:如果您在 Go playground 上运行您的应用程序,它还指示您的应用程序的退出状态(无输出):

Program exited: status 2.

这个“问题”以前被提出过,见#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.

Dmitri Shuralyov 的话:

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.

关于Go os.Exit(2) 显示一个 bash $?值为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55731760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com