golang 通过管道连接两个命令行进程
原理:
1
2
3
4
5
generator := exec.Command("cmd1")
consumer := exec.Command("cmd2")
pipe, err := consumer.StdinPipe()
generator.Stdout = pipe
完整实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import (
"os"
"os/exec"
)
func main() {
c1 := exec.Command("ls")
c2 := exec.Command("wc", "-l")
c2.Stdin, _ = c1.StdoutPipe()
c2.Stdout = os.Stdout
_ = c2.Start()
_ = c1.Run()
_ = c2.Wait()
}
还有一个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main
import (
"bytes"
"io"
"os"
"os/exec"
)
func main() {
c1 := exec.Command("ls")
c2 := exec.Command("wc", "-l")
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)
}
本文网址: https://golangnote.com/topic/60.html 转摘请注明来源