Skip to content

Instantly share code, notes, and snippets.

@szaydel
Created September 11, 2015 19:03
Show Gist options
  • Save szaydel/446413da7fe8749a4461 to your computer and use it in GitHub Desktop.
Save szaydel/446413da7fe8749a4461 to your computer and use it in GitHub Desktop.
Access StdIn of Exec'd process with Golang
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, What's your favorite number?")
var i int
fmt.Scanf("%d\n", &i)
fmt.Println("Ah I like ", i, " too.")
}
package main
import (
"fmt"
"io"
"os"
"os/exec"
)
func main() {
subProcess := exec.Command("go", "run", "./helper/main.go") //Just for testing, replace with your subProcess
stdin, err := subProcess.StdinPipe()
if err != nil {
fmt.Println(err) //replace with logger, or anything you want
}
defer stdin.Close() // the doc says subProcess.Wait will close it, but I'm not sure, so I kept this line
subProcess.Stdout = os.Stdout
subProcess.Stderr = os.Stderr
fmt.Println("START") //for debug
if err = subProcess.Start(); err != nil { //Use start, not run
fmt.Println("An error occured: ", err) //replace with logger, or anything you want
}
io.WriteString(stdin, "4\n")
subProcess.Wait()
fmt.Println("END") //for debug
}
@Zeg0
Copy link

Zeg0 commented Apr 25, 2023

for some subprocess you need to close stdin to indicate all data has been send.

for example if you use ubuntu base64 tool in line 11 and you want to pipe some data to it you need to change line 27-29 like this:

...
 subProcess := exec.Command("/usr/bin/base64")
 ...
 io.WriteString(stdin,`multiline
 text
 file
 content`)
 stdin.Close() // <--- indicate that we piped all data we want!
 subProcess.Wait()
 fmt.Println("END") 

this will behave exactly like cat myfile.txt | base64 with the given file content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment