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
+8.8k Golang : Go as a script or running go with shebang/hashbang style
+16.4k Golang : Read integer from file into array
+19.8k Golang : Reset or rewind io.Reader or io.Writer
+41.2k Golang : Convert string to array/slice
+10k Golang : Embed secret text string into binary(executable) file
+13.5k Golang : Tutorial on loading GOB and PEM files
+6.8k Golang : constant 20013 overflows byte error message
+8k Golang : Add build version and other information in executables
+16.2k Golang : How to implement two-factor authentication?
+11.1k Golang : Characters limiter example
+15k Golang : Get query string value on a POST request