How to use a file as stdin when exec a command

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

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(&quot;cat&quot;)
cmd.Stdout = os.Stdout
stdin, _ := cmd.StdinPipe()
file, _ := os.Open(&quot;file&quot;)
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 &lt;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 就会终止。

另外,我知道这只是一个示例,但是完全没有错误检查。我猜这只是为了说明目的。 How to use a file as stdin when exec a command

英文:

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. How to use a file as stdin when exec a command

huangapple
  • 本文由 发表于 2017年7月25日 20:12:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/45302931.html
匿名

发表评论

匿名网友

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

确定