Go 系统命令管道操作

Go系统命令管道操作

go 执行系统命令时不能直接使用管道符 |

实现方法如下:

方法一(同步)

func sync() {
    cmd1 := exec.Command("ls", ".")
    cmd2 := exec.Command("grep", "go")
    cmd2.Stdout = os.Stdout
    in, _ := cmd2.StdinPipe()
    cmd1.Stdout = in
    cmd2.Start()
    cmd1.Run()
    in.Close()
    cmd2.Wait()
}

方法二(异步)

func async() {
    cmd1 := exec.Command("ls", ".")
    cmd2 := exec.Command("grep", "go")
    cmd2.Stdout = os.Stdout
    out, _ := cmd1.StdoutPipe()
    in, _ := cmd2.StdinPipe()
    go func() {
        defer func() {
            out.Close()
            in.Close()
        }()
        io.Copy(in, out)
    }()
    cmd1.Run()
    cmd2.Run()
}

方法三(串联)

func main() {
    cmd1 := exec.Command("ls", ".")
    cmd2 := exec.Command("grep", "go")
    cmd3 := exec.Command("grep", "main")
    cmd3.Stdout = os.Stdout
    pipe(cmd1, cmd2, cmd3)
    cmd1.Run()
    cmd2.Run()
    cmd3.Run()
}

func pipe(cmds ...*exec.Cmd) {
    for i, cmd := range cmds {
        if i > 0 {
            out, _ := cmds[i-1].StdoutPipe()
            in, _ := cmd.StdinPipe()
            go func() {
                defer func() {
                    out.Close()
                    in.Close()
                }()
                io.Copy(in, out)
            }()
        }
    }
}

欢迎各位同学学习交流。

[阅读原文]

本作品采用《CC 协议》,转载必须注明作者和本文链接
awesee
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!