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
+15.7k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+3.5k Golang : Fix go-cron set time not working issue
+7.5k Golang : Get YouTube playlist
+15k Golang : How to check for empty array string or string?
+7.5k Golang : Convert source code to assembly language
+9.4k Golang : Temperatures conversion example
+19.7k Golang : Close channel after ticker stopped example
+17.8k Golang : Read data from config file and assign to variables
+7.5k Golang : Example of custom handler for Gorilla's Path usage.
+14k Golang : Get dimension(width and height) of image file
+19k Golang : Read input from console line
+7.1k Web : How to see your website from different countries?