dqnhfbc3738 2018-06-06 14:34
浏览 470
已采纳

Golang中多个程序之间的交互

I'm trying to have two golang programs communicating using pipes, each running concurrently e.g:

1 go run master/main/main.go 

2 master/main/main.go calls slave.exe (built go program)

3 slave.exe prints out "Ping"

4 master/main/main.go reads "Ping" and writes "Pong"

5 slave.exe reads "Pong" and prints out "Message recieved: Pong"

The program reaches step 4 but it does not receive another message from slave.exe.

In master/main/main.go:

package main

import (
    "fmt"
    "os"
    "os/exec"
    "bufio"
)

func main() {
    // Run compiled slave project:
    c := exec.Command("main", insert_path_to_exe_here)

    out, _ := c.StdoutPipe()
    in, _ := c.StdinPipe()

    c.Start() // Using Start() instead of Run() because Run() waits for program to finish before moving on.

    inwriter := bufio.NewWriter(in)
    outreader := bufio.NewReader(out)

    // This should print "Ping".
    fmt.Println(outreader.ReadString('
'))

    inwriter.WriteString("Pong")

    // This should print "Message received: Pong"
    fmt.Println(outreader.ReadString('
'))

}

In slave/main/main.go:

package main

import (
    "fmt"
    "bufio"
    "os"
)

func main() {
    fmt.Println("Ping")
    reader := bufio.NewReader(os.Stdin)

    s, _ := reader.ReadString('
')

    fmt.Println("Message received: ", s)
}

To run:

  • Build slave/main/main.go
  • Replace insert_path_to_exe_here with the path to the built executable and replace "main" with the name of the executable.
  • Run master/main/main.go
  • 写回答

1条回答 默认 最新

  • duanbo5230 2018-06-06 14:48
    关注

    Your subprocess is using ReadString(' '), but you aren't writing a character, nor are you flushing the buffered writer.

    This will write the expected data to the pipe:

    inwriter.WriteString("Pong
    ")
    inwriter.Flush()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流