检测是否有内容输入到标准输入(STDIN)中。

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

Detecting whether something is on STDIN

问题

以下是要翻译的内容:

程序应该能够从终端的stdin获取输入,如下所示:

echo foobar | program

然而,在下面的程序源代码中,如果省略了管道,stdin读取将会阻塞:

package main

import (
	"fmt"
	"os"
)

func main() {
	b := make([]byte, 1024)
	r := os.Stdin
	n, e := r.Read(b)
	if e != nil {
		fmt.Printf("Err: %s\n", e)
	}
	fmt.Printf("Res: %s (%d)\n", b, n)

}

那么,程序如何检测是否以这种方式将某些内容传递给它,并在没有传递内容时继续执行而不阻塞呢?

...这样做是个好主意吗?

英文:

Program should be able to get input from stdin on terminal, as follows:

echo foobar | program

However, in the source below for Program, the stdin read blocks if the pipe is omitted:

package main

import (
	"fmt"
	"os"
)

func main() {
	b := make([]byte, 1024)
	r := os.Stdin
	n, e := r.Read(b)
	if e != nil {
		fmt.Printf("Err: %s\n", e)
	}
	fmt.Printf("Res: %s (%d)\n", b, n)

}

So how can Program detect whether something is being piped to it in this manner, and continue execution instead of blocking if not?

... and is it a good idea to do so?

答案1

得分: 1

os.Stdin 被视为文件并具有权限。当 os.Stdin 打开时,权限为 0600,当关闭时为 0620

以下是代码的翻译:

package main

import (
	"fmt"
	"os"
)

func main() {
	stat, _ := os.Stdin.Stat()
	fmt.Printf("标准输入模式: %v\n", stat.Mode().Perm())
	if stat.Mode().Perm() == 0600 {
		fmt.Printf("标准输入已打开\n")
		return
	}
	fmt.Printf("标准输入已关闭\n")

}

希望对你有帮助!

英文:

os.Stdin is treated like a file and has permissions. When os.Stdin is open, the perms are 0600, when closed it's 0620.

This code works:

package main

import (
	"fmt"
	"os"
)

func main() {
	stat, _ := os.Stdin.Stat()
	fmt.Printf("stdin mode: %v\n", stat.Mode().Perm())
	if stat.Mode().Perm() == 0600 {
		fmt.Printf("stdin open\n")
		return
	}
	fmt.Printf("stdin close\n")

}

答案2

得分: 0

如果你将读取操作放在一个 goroutine 中,并在主函数中使用 select 进行非阻塞读取通道,那么这是可能的。但是这样会导致竞态条件,取决于数据是否足够快地到达,你可能会得到不同的结果。你试图解决的更大问题是什么?

英文:

It would be possible if you put the read in a goroutine and use select to do a non-blocking read from the channel in main, but you would then have a race condition where you could get different results depending on whether the data comes in quickly enough. What is the larger problem you're trying to solve?

huangapple
  • 本文由 发表于 2017年3月5日 07:31:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/42602606.html
匿名

发表评论

匿名网友

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

确定