Here are some examples of writing and reading code:
package main
import (
"bufio"
"fmt"
"os/exec"
)
func main() {
calcs := make([]string, 2)
calcs[0] = "3*3"
calcs[1] = "6+6"
results := make([]string, 2)
cmd := exec.Command("/usr/bin/bc")
in, err := cmd.StdinPipe()
if err != nil {
panic(err)
}
defer in.Close()
out, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
defer out.Close()
bufOut := bufio.NewReader(out)
if err = cmd.Start(); err != nil {
panic(err)
}
for _, calc := range calcs {
_, err := in.Write([]byte(calc + "\n"))
if err != nil {
panic(err)
}
}
for i := 0; i < len(results); i++ {
result, _, err := bufOut.ReadLine()
if err != nil {
panic(err)
}
results[i] = string(result)
}
for _, result := range results {
fmt.Println(result)
}
}
You might want to read / write / from a process in different goroutines.
source
share