先尝试在exec代码直接加管道
```
cmd := exec.Command("ps","-ef","|","grep", "proc")
```
毫无疑问,运行报错,所以肯定不是直接这么写。
因为cmd可以配置Stdin。其实就是我们要执行命令的输入。于是在运行第二条命令的时候可以用第一条命令的Stdout
代码如下:
```
c1 := exec.Command("ps","-ef")
c2 := exec.Command("grep", "proc")
c2.Stdin, _ = c1.StdoutPipe()
c2.Stdout = os.Stdout
_ = c2.Start()
_ = c1.Run()
_ = c2.Wait()
```
当然,就是将io.Reader转换成io.Writer.于是还可以这么写:
```
c1 := exec.Command("ps","-ef")
c2 := exec.Command("grep", "proc")
r, w := io.Pipe()
c1.Stdout = w
c2.Stdin = r
var b2 bytes.Buffer
c2.Stdout = &b2
c1.Start()
c2.Start()
c1.Wait()
w.Close()
c2.Wait()
io.Copy(os.Stdout, &b2)
```
原文:http://wordpress-1-edcapdingshn5.tenxapp.com/2015/12/04/golang-exec-pipe/
有疑问加站长微信联系(非本文作者)