如何将io.Stdin和io.Stdout传递给exec.Command

时间:2016-12-06 14:33:21

标签: go exec

我试图读写public class MyFragment extends Fragment { public String mTitle; public String mInitialTitle; public static MyFragment newInstance(String param1) { MyFragment f = new MyFragment(); f.mInitialTitle = param1; f.mTitle = param1; return f; } @Override public void onSaveInstanceState(Bundle state) { state.putString("mInitialTitle", mInitialTitle); state.putString("mTitle", mTitle); super.onSaveInstanceState(state); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { if (state != null) { mInitialTitle = state.getString("mInitialTitle"); mTitle = state.getString("mTitle"); } ... } } ,但我正在努力管道。

第一个是我想要的行为的一个例子。 go应用程序只是将stdin,stdout和stderr代理到命令:

exec.Command

运行它就像:

package main

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

func main() {
    cmd := exec.Command("bash", "-i")

    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    cmd.Run()
    fmt.Println("Done")
}

但是这个根本不起作用:

pensarando@home: ~/go/src/test$ ./test
pensarando@home: ~/go/src/test$ echo "hello"
hello
pensarando@home: ~/go/src/test$ exit
Done
pensarando@home: ~/go/src/test$ 

当我从终端运行这个时,输出例如是:

package main

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

func main() {
    cmd := exec.Command("bash", "-i")

    in, _ := cmd.StdinPipe()
    out, _ := cmd.StdoutPipe()
    err, _ := cmd.StderrPipe()

    exit := make(chan struct{})

    done := func() {
        in.Close()
        out.Close()
        err.Close()
        cmd.Wait()
        close(exit)
    }

    var once sync.Once

    go func() {
        io.Copy(os.Stdout, out)
        fmt.Println("done stdout")
        once.Do(done)
    }()

    go func() {
        io.Copy(in, os.Stdin)
        fmt.Println("done stdin")
        once.Do(done)
    }()

    go func() {
        io.Copy(os.Stderr, err)
        fmt.Println("done stderr")
        once.Do(done)
    }()

    cmd.Start()
    <-exit
    fmt.Println("Done")
}

这里到底发生了什么?

0 个答案:

没有答案