Answer the question
In order to leave comments, you need to log in
How to pass data from go to a subprocess (via exec.Command), but without restarting the subprocess (i.e. write/read all the time)?
There is this code:
cfCmd := exec.Command("perl", "./test.pl")
cfIn, _ := cfCmd.StdinPipe()
cfOut, _ := cfCmd.StdoutPipe()
err := cfCmd.Start()
if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
cfIn.Write([]byte(task))
cfIn.Close()
cfBytes, _ := ioutil.ReadAll(cfOut)
cfCmd.Wait()
res := "\n>>> Server: test.pl " + fmt.Sprint(id) + " вернул: \n" + string(cfBytes)
Answer the question
In order to leave comments, you need to log in
Do not close cfIn, write data there, but read from cfOut, in different goroutines.
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"strings"
)
func main() {
cfCmd := exec.Command("perl", "test.pl")
cfIn, err := cfCmd.StdinPipe()
if err != nil {
panic(err)
}
cfOut, err := cfCmd.StdoutPipe()
if err != nil {
panic(err)
}
err = cfCmd.Start()
if err != nil {
panic(err)
}
go ProcessStdin(cfIn)
ProcessStdout(cfOut)
err = cfCmd.Wait()
if err != nil {
panic(err)
}
}
func ProcessStdin(stdin io.WriteCloser) {
defer stdin.Close()
stdin.Write([]byte("some task"))
stdin.Write([]byte("some other task"))
// ......
}
func ProcessStdout(stdout io.ReadCloser) {
defer stdout.Close()
rd := bufio.NewReader(stdout)
for {
line, err := rd.ReadString('\n')
if err != nil {
fmt.Println("Error reading stdout:", err)
os.Exit(1)
}
line = strings.TrimSpace(line)
fmt.Println("Got line from a process:", line)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question