管道传输多个命令,然后写入文件

时间:2018-11-16 23:51:39

标签: go

我正在尝试通过管道传输多个*exec.Cmd,然后写入文件。当我尝试使用一个cmd并输出到文件时,它将写入文件。但是,当我尝试使用多个命令并输出到文件时,却没有。但是exec.Cmd似乎正在传递,因为它可以正确输出。

outfile, err := os.Create("./out.txt")
if err != nil {
    panic(err)
}
defer outfile.Close()

c1 := exec.Command("sh", "-c", "while sleep 1; do echo test; done")
c1.Stdout = outfile
_ = c1.Run()

for {

}

上面的代码每秒钟写入一次文件。 但是当我尝试这样做时:

outfile, err := os.Create("./out.txt")
if err != nil {
    panic(err)
}
defer outfile.Close()

c1 := exec.Command("sh", "-c", "while sleep 1; do echo test; done")
c2 := exec.Command("grep", "t")
c2.Stdin, _ = c1.StdoutPipe()
c2.Stdout = outfile
_ = c2.Start()
_ = c1.Run()
c2.Wait()

这不会输出任何内容。

但是当我将c2.Stdout = outfile更改为c2.Stdout = os.Stdout时,它会正确打印输出

我不知道为什么会这样。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

因此,grep并未注意到它正在写入常规文件。

通过以下方式更改此行:

c2 := exec.Command("grep", "t")

这可以正常工作并正确写入文件

c2 := exec.Command("grep", "t", "--line-buffered")
相关问题