(note) not a dupe of Go Inter-Process Communication which is asking about System V IPC. (end note)
Using os/exec
, how do I interactively communicate with another process? I'd like to get fd's for the process's stdin and stdout, and write to and read from the process using those fds.
Most examples I have found involve running another process and then slurping the resulting output.
Here's the python equivalent of what I'm looking for.
p = subprocess.Popen("cmd", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
As a tangible example, consider opening a pipe to dc, sending the line 12 34 +p
and receiving the line 46
.
(update)
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)
}
I see by strace that dc
is receiving and answering as expected:
[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 ...>
but I don't seem to be getting the results back into my calling program:
0 ::
(update)
As per the accepted answer, my problem was not allocating the string to receive the response. Changing to line := make([]byte, 100)
fixed everything.