英文:
How to use a file as stdin when exec a command
问题
我有这段非常简单的代码:
cmd := exec.Command("cat")
cmd.Stdout = os.Stdout
stdin, _ := cmd.StdinPipe()
file, _ := os.Open("file")
io.Copy(stdin, file)
_ = cmd.Run()
它可以正常工作。但问题是cmd.Run()
永远不会返回。似乎在将文件写入stdin后,cat
仍然在等待更多内容。
我正在尝试实现cat <file
的功能,这种情况下,cat
在读取完文件后会退出。
我想知道如何在Go语言中实现这一点?
英文:
I have this very simple code:
cmd := exec.Command("cat")
cmd.Stdout = os.Stdout
stdin, _ := cmd.StdinPipe()
file, _ := os.Open("file")
io.Copy(stdin, file)
_ = cmd.Run()
It works. But the problem is that cmd.Run()
never returns. It seems after writing the file to stdin, cat
still waits for more content.
I'm trying to do what cat <file
does, in which case cat
would exit after reading the file.
I wonder how to achieve that in go?
答案1
得分: 3
这是因为你没有关闭 stdin。在 io.Copy
之后添加 stdin.Close()
。然后 cat
就会终止。
另外,我知道这只是一个示例,但是完全没有错误检查。我猜这只是为了说明目的。
英文:
It's because you you don't close the stdin. Add stdin.Close()
after io.Copy
. cat
will then terminate.
Also, I know it's just an example but there is absolutely no error checking. I assume that's just for illustration purposes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论