Go:与另一个进程进行双向通信?

时间:2016-09-30 20:13:44

标签: go popen

(注意)不是Go Inter-Process Communication的问题,而是询问System V IPC。 (尾注)

使用os/exec,如何与其他流程进行交互式通信?我想为进程的stdin和stdout获取fd,并使用这些fds写入和读取进程。

我发现的大多数示例都涉及运行另一个进程,然后啜饮结果输出。

这是python相当于我正在寻找的东西。

p = subprocess.Popen("cmd", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)

作为一个切实的示例,请考虑将管道打开到直流,发送行12 34 +p并接收行46

(更新)

func main() {
  cmd := exec.Command("dc")
  stdin, err := cmd.StdinPipe()
  must(err)
  stdout, err := cmd.StdoutPipe()
  must(err)

  err = cmd.Start()
  must(err)

  fmt.Fprintln(stdin, "2 2 +p")

  line := []byte{}
  n, err := stdout.Read(line)

  fmt.Printf("%d :%s:\n", n, line)
}

我通过strace看到dc正在按预期接收和回答:

[pid  8089] write(4, "12 23 +p\n", 9 <unfinished ...>
...
[pid  8095] <... read resumed> "12 23 +p\n", 4096) = 9
...
[pid  8095] write(1, "35\n", 3 <unfinished ...>

但我似乎没有将结果反馈到我的调用程序中:

0 ::

(更新)

根据接受的答案,我的问题是没有分配字符串来接收响应。更改为line := make([]byte, 100)修复所有内容。

1 个答案:

答案 0 :(得分:4)

exec.Cmd包含您可以分配的进程stdin,std和stderr的字段。

    // Stdin specifies the process's standard input.
    // If Stdin is nil, the process reads from the null device (os.DevNull).
    // If Stdin is an *os.File, the process's standard input is connected
    // directly to that file.
    // Otherwise, during the execution of the command a separate
    // goroutine reads from Stdin and delivers that data to the command
    // over a pipe. In this case, Wait does not complete until the goroutine
    // stops copying, either because it has reached the end of Stdin
    // (EOF or a read error) or because writing to the pipe returned an error.
    Stdin io.Reader

    // Stdout and Stderr specify the process's standard output and error.
    //
    // If either is nil, Run connects the corresponding file descriptor
    // to the null device (os.DevNull).
    //
    // If Stdout and Stderr are the same writer, at most one
    // goroutine at a time will call Write.
    Stdout io.Writer
    Stderr io.Writer

如果您希望将预制管道连接到其中任何一个,您可以使用*Pipe()方法

func (c *Cmd) StderrPipe() (io.ReadCloser, error)
func (c *Cmd) StdinPipe() (io.WriteCloser, error)
func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

使用dc程序的基本示例(无错误检查):

cmd := exec.Command("dc")
stdin, _ := cmd.StdinPipe()
stdout, _ := cmd.StdoutPipe()
cmd.Start()

stdin.Write([]byte("12 34 +p\n"))

out := make([]byte, 1024)
n, _ := stdout.Read(out)

fmt.Println("OUTPUT:", string(out[:n]))

// prints "OUTPUT: 46"