K
K
Konvergent2019-04-04 18:48:12
go
Konvergent, 2019-04-04 18:48:12

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)

But the problem is that I only need to run test.pl once, and then write data to it and read responses.
How to do it correctly in golang?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2019-04-04
@pav5000

Do not close cfIn, write data there, but read from cfOut, in different goroutines.

For example, so
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)
  }
}

Don't forget to do it in your perl program.
Otherwise, perl won't flush the stdout buffer and you won't get anything in the interactive.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question