英文:
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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论