dorbmd1177 2018-11-16 23:51 采纳率: 100%
浏览 117

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

I'm trying to pipe multiple *exec.Cmd and then write to file. When I try with one cmd and output to file, it writes to the file. However, when I try with multiple commands and output to file, it does not. But the exec.Cmd seems to be piping as it can stdout correctly.

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 {

}

This above code writes to file every one second. But when I try this:

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()

This does not output anything.

But when I change c2.Stdout = outfile to c2.Stdout = os.Stdout, then it prints out the output correctly

I can't figure out why this is happening. Any help appreciated.

  • 写回答

1条回答 默认 最新

  • dou12754 2018-11-17 01:36
    关注

    So, the grep is not noticing that it's writing to a regular file.

    By changing this line from:

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

    to this works and writes to the file correctly

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

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算