Reputation: 31
How can I run a binary file in my golang program and keep interacting with it by sending some input and waiting for the output? In what I did, I run it only once. And I want to keep this binary file running and interact with it, I don't want to run it multiple times.
package main
import (
"os/exec"
"bytes"
"fmt"
)
func main() {
command := exec.Command("./program")
var output bytes.Buffer
command.Stdout = &output
command.Run()
result := output.String()
IV := result[:4]
cipher := result[5:]
cipher = cipher[:len(cipher)-1]
fmt.Printf("%v", result)
fmt.Printf("%v", IV)
fmt.Printf("%v", cipher)
}
Upvotes: 3
Views: 2350
Reputation: 273396
I believe the right way to accomplish this is using the StdinPipe
and StdoutPipe
methods of exec.Cmd
.
See examples in https://golang.org/pkg/os/exec/#Cmd.StdinPipe, etc.
Here's an example that invokes the bc
command (built-in calculator that takes calculations from stdin and emits results to stdout) and interacts with it a bit:
package main
import (
"bufio"
"fmt"
"log"
"os/exec"
)
func main() {
cmd := exec.Command("bc", "-q")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
stdin.Write([]byte("2 + 2\n"))
r := bufio.NewReader(stdout)
b, err := r.ReadBytes('\n')
if err != nil {
log.Fatal(err)
}
fmt.Println("Read:", string(b))
}
In a real program you may want to run this thing in a goroutine so it doesn't block the rest of the application, happens in the background, etc.
Upvotes: 1