func CmdPipeRun(cmdS ...*exec.Cmd) (stdout, stderr *bytes.Buffer, err error) {
var out io.ReadCloser
var in io.WriteCloser
for i, cmd := range cmdS {
if i > 0 {
// 上一個指令的輸出
out, err = cmdS[i-1].StdoutPipe()
if err != nil {
return
}
// 當前指令的輸入
in, err = cmd.StdinPipe()
if err != nil {
return
}
// 阻塞指令進行,直到 Close()
go cmdPipe(cmdS[i-1], out, in)
}
if i == len(cmdS)-1 {
stdout, stderr = SetCommandStd(cmd)
}
}
for _, cmd := range cmdS {
err = cmd.Run()
if err != nil {
return
}
}
return
}
func cmdPipe(cmd *exec.Cmd, r io.ReadCloser, w io.WriteCloser) {
defer func() {
_ = r.Close()
_ = w.Close()
}()
_, err := io.Copy(w, r)
if err != nil {
fmt.Println("error: ", err)
}
return
}