4

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)
}
5
  • 2
    Go aside, how do you currently interact with your program? Stdin / Stdout? Pipes? Sockets? Commented Feb 6, 2019 at 1:24
  • I don't know how this could work, that is what I'm trying to figure out. I wish someone could guide me in this. The binary that I'm trying to interact with receives an input and give and output and waits for another input. So what I want to do is interacting with it in that way. Commented Feb 6, 2019 at 1:36
  • It sounds like you are interacting with stdin and stdout then. Take a look here: stackoverflow.com/questions/36382880/… Commented Feb 6, 2019 at 1:40
  • I'm trying stdin, but I don't know how I can write to the binary not to my program. Commented Feb 6, 2019 at 1:43
  • Oh, I will try this. Thank you so much! Commented Feb 6, 2019 at 1:44

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.