Golang : How to pipe input data to executing child process?
Problem :
Your program is executing a child process via os/exec
and you want to pipe input data to the executing process.
Solution :
Use the StdinPipe()
method and issue a .Write([]byte(your data))
to input data to the executing child process.
For example :
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("cat")
stdin, err := cmd.StdinPipe()
stdin.Write([]byte("Hello World!")) // <------ here
stdin.Close()
if err != nil {
panic(err)
}
data, err := cmd.Output()
if err != nil {
panic(err)
}
for k, v := range data {
fmt.Printf("key : %v, value : %v \n", k, string(v))
}
}
See also : Golang : Pipe output from one os.Exec(shell command) to another command
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.4k SSL : How to check if current certificate is sha1 or sha2
+5.6k Golang : Launching your executable inside a console under Linux
+4.5k Facebook : How to place save to Facebook button on your website
+12.2k Golang : Search and extract certain XML data example
+11.8k Golang : Pagination with go-paginator configuration example
+16.1k Golang : Check if a string contains multiple sub-strings in []string?
+10.3k Golang : Create matrix with Gonum Matrix package example
+15.9k Golang : Loop each day of the current month example
+29k Golang : Record voice(audio) from microphone to .WAV file
+7.6k Golang : Regular Expression find string example
+15.4k Golang : Get current time from the Internet time server(ntp) example
+17.9k Golang : Get command line arguments