Go在Windows中如何处理标准输出(stdout)?

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

How does Go handle stdout in Windows?

问题

我在查看Go的源代码时发现,标准输出(os.Stdout)指向:

os.Stdout = os.NewFile(uintptr(syscall.Stdout), "/dev/stdout")

但据我理解,这应该只适用于基于Unix的系统。然而,它被定义为一个通用变量。

英文:

I was checking in Go's source code, and it seems the standard out (os.Stdout) points to:

os.Stdout = os.NewFile(uintptr(syscall.Stdout), "/dev/stdout")

But from my understanding, this should only work for Unix-based systems. And yet, it's defined as a general variable.

答案1

得分: 5

Microsoft表示,Windows具有标准输出设备(stdout)。

> GetStdHandle函数
>
> STD_OUTPUT_HANDLE - 标准输出设备。

Windows特定的Go syscall.Stdout 变量位于:

go/src/syscall/syscall_windows.go:

var (
	Stdout = getStdHandle(STD_OUTPUT_HANDLE)
)

有关特定于操作系统的文件,请参阅Go构建约束

英文:

Microsoft says Windows has a standard output device (stdout).

> GetStdHandle function
>
> STD_OUTPUT_HANDLE - The standard output device.

The Windows specific Go syscall.Stdout variable is:

go/src/syscall/syscall_windows.go:

var (
	Stdout = getStdHandle(STD_OUTPUT_HANDLE)
)

See Go Build constraints for OS specific files.

答案2

得分: 3

NewFile函数传递的主要重要参数是第一个参数,即文件句柄。Windows的syscall包正确地为标准输出文件(syscall.Stdout)指定了一个值,因此os只是借用它。

第二个参数的目的只是为了给生成的*os.File值一个可以使用的名称,例如在调用os.Stdout.Name()时使用,因为文件句柄本身不带有名称。你可以认为在Windows上将os.Stdout命名为"/dev/stdout"是令人困惑的,但这只是一个不影响功能的名称。

英文:

The main important argument passed to NewFile is the first one, which is the file handle. The Windows syscall package correctly specifies a value for the standard output file (syscall.Stdout), so os just borrows it.

The point of the second argument is just to give the resulting *os.File value some kind of name that can be used, for example when calling os.Stdout.Name(), since the file handle doesn't carry a name by itself. You could argue that naming os.Stdout as "/dev/stdout" on Windows is confusing, but it's just a name that doesn't impact functionality.

huangapple
  • 本文由 发表于 2023年2月15日 06:46:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75453941.html
匿名

发表评论

匿名网友

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

确定