GolangNote

Golang笔记

golang 通过管道连接两个命令行进程

Permalink

golang 通过管道连接两个命令行进程

golang 通过管道连接两个命令行进程

原理:

Go: 原理
1
2
3
4
5
generator := exec.Command("cmd1")
consumer := exec.Command("cmd2")

pipe, err := consumer.StdinPipe()
generator.Stdout = pipe

完整实例:

Go: exec pip
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()
}

还有一个例子:

Go: Command
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 转摘请注明来源

Related articles

golang共享数据用Mutex 或 Channel

在go 里,多线程对共享数据的操作一般要使用Mutex 或 Channel 来加锁或隔离通信。下面是一个使用Mutex 和 Channel 比较的例子。...

Golang 时区时差处理方式

个人习惯用 0 时区时间戳记录时间,可以方便转到不同时区,下面介绍 Golang 时区时差处理...

Write a Comment to "golang 通过管道连接两个命令行进程"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms