dongmei1828 2019-02-06 00:59
浏览 92

如何在golang程序中运行二进制文件并通过发送一些输入并等待输出来保持与之交互?

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)
}
  • 写回答

1条回答 默认 最新

  • dongliushui2001 2019-02-06 13:49
    关注

    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
    "))
    
        r := bufio.NewReader(stdout)
        b, err := r.ReadBytes('
    ')
        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.

    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码