go - Golang 中多个程序之间的交互

标签 go

我正在尝试让两个 golang 程序使用管道进行通信,每个程序同时运行,例如:

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"

程序到达第 4 步,但没有收到来自 slave.exe 的另一条消息。

在 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('\n'))

    inwriter.WriteString("Pong")

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

}

在 slave/main/main.go 中:

package main

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

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

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

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

运行:

  • 构建slave/main/main.go
  • 将 insert_path_to_exe_here 替换为构建的可执行文件的路径,并将“main”替换为可执行文件的名称。
  • 运行 master/main/main.go

最佳答案

您的子进程正在使用 ReadString('\n'),但您没有编写 \n 字符,也没有刷新缓冲的编写器。

这会将预期的数据写入管道:

inwriter.WriteString("Pong\n")
inwriter.Flush()

关于go - Golang 中多个程序之间的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50723053/

相关文章:

Go:将 argv 传递给 C 函数

Go gRPC status.Error() 在运行并发请求时导致无效的内存地址

angularjs - 来自浏览器的 Ajax 不起作用,但来自 PostMan 的有效

tsql - 是否可以在一次交易中调用Go函数?

go - 不正确的包名称不会在构建时抛出错误

go - 运行 dep 时出错确保 : Grouped write of manifest, 锁和 vendor :无法统计 VerifyVendor 声称存在的文件

for-loop - 在 golang 中写 while (for) 的更好方法

使用根级别元素解析 XML

go - 在golang中将结构转换为字节数据,反之亦然

switch-statement - 为什么在类型开关中不允许掉线?