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

Go 通过管道传输多个命令,然后写入文件,go,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 sle

我正在尝试通过管道传输多个
*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
时,它会正确地打印输出

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

我不明白为什么会这样。感谢您的帮助。

因此,grep没有注意到它正在写入常规文件

通过将此行从:

c2 := exec.Command("grep", "t")
这样可以正常工作并正确写入文件

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

可能
grep
注意到它正在写入一个常规文件,并对输出进行块缓冲。@williampersell谢谢!这让我找到了下面的解决方案