MDGSF Software Engineer

[GO] exec command

2018-05-16
GO

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "os/exec"
)

func main() {
    run3()
}

func run1() {
    c1 := exec.Command("ps", "-A")
    c2 := exec.Command("grep", "vim")
    c2.Stdin, _ = c1.StdoutPipe()
    //c2.Stdout = os.Stdout

    outPipe, err := c2.StdoutPipe()
    if err != nil {
        fmt.Println(err)
        return
    }

    c2.Start()
    c1.Run()

    content, err := ioutil.ReadAll(outPipe)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(string(content))

    c2.Wait()
}

func run2() {
    cmd := exec.Command("/bin/sh", "-c", `ps -A | grep vim`)
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.Start()
    cmd.Run()
    cmd.Wait()
}

func run3() {
    cmd := exec.Command("/bin/sh", "-c", `ps -A | grep vim`)
    output, _ := cmd.Output()
    fmt.Println(string(output))
}

weixingongzhonghao

上一篇 [GO] go get proxy

Comments

Content