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 实现的基于web的文件管理-filebrowser

FileBrowser 在指定目录中提供了一个文件管理界面,可用于上传,删除,预览,重命名和编辑文件。它允许创建多个用户,每个用户都可以有自己的目录。它可以用作独立的应用程序。...

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

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

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