exec.Command管道实现循环输入

hipeace86 · · 3943 次点击
解决方案如下: ``` 1 DecodeCmd = exec.Command("code.exe") 2 pipIn, _ := rabbit.DecodeCmd.StdinPipe() 3 pipOut, _ := rabbit.DecodeCmd.StdoutPipe() 4 DecodeCmd.Start() 5 CmdBufReader = bufio.NewReader(pipOut) 6 CmdBufWriter = bufio.NewWriter(pipIn) 7 8 CmdBufWriter.WriteString(fmt.Sprintf("%s\n", "35063812556aa2cdd6d1cbd")) 9 CmdBufWriter.Flush() 10 code, _, _ := r.CmdBufReader.ReadLine() 11 CmdBufWriter.WriteString(fmt.Sprintf("%s\n", "350632125e6aa2cdded1c")) 12 CmdBufWriter.Flush() 13 code, _, _ = r.CmdBufReader.ReadLine() ```
#4
更多评论
stevewang
耶和华是我的牧者,我必不至缺乏。
`cmd.Run()`返回以后,子进程都已经结束了。
#1
stevewang
耶和华是我的牧者,我必不至缺乏。
供参考: ``` package main import ( "bufio" "fmt" "io" "os/exec" ) func encode(r *bufio.Reader, w io.Writer, str string) string { w.Write([]byte(str)) w.Write([]byte("\n")) str, err := r.ReadString('\n') if err != nil { panic(err) } // skip '\n' return str[:len(str)-1] } func main() { cmd := exec.Command(`./code.exe`) inr, inw := io.Pipe() outr, outw := io.Pipe() cmd.Stdin = inr cmd.Stdout = outw if err := cmd.Start(); err != nil { panic(err) } go cmd.Wait() strs := []string{ "35063812556aa2cdd6d1cbd", "350632125e6aa2cdded1c", } for _, str := range strs { result := encode(bufio.NewReader(outr), inw, str) fmt.Println(result) } } ```
#2