Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VimleshS/7bba68f7263353921258e31b3313c234 to your computer and use it in GitHub Desktop.
Save VimleshS/7bba68f7263353921258e31b3313c234 to your computer and use it in GitHub Desktop.
Using stdout and stdin from other programs in Golang

Go program interaction

Example of how to use stdout and stdin from other programs in golang

Requires go

Run

go run parentprocess.go
package main
import (
"bufio"
"io"
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("./subprocess.sh")
cmd.Stderr = os.Stderr
stdin, err := cmd.StdinPipe()
if nil != err {
log.Fatalf("Error obtaining stdin: %s", err.Error())
}
stdout, err := cmd.StdoutPipe()
if nil != err {
log.Fatalf("Error obtaining stdout: %s", err.Error())
}
reader := bufio.NewReader(stdout)
go func(reader io.Reader) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
log.Printf("Reading from subprocess: %s", scanner.Text())
stdin.Write([]byte("some sample text\n"))
}
}(reader)
if err := cmd.Start(); nil != err {
log.Fatalf("Error starting program: %s, %s", cmd.Path, err.Error())
}
cmd.Wait()
}
#!/bin/bash
echo "Enter some text:"
read -r input
echo "you typed: $input"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment