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
+14.7k Golang : Get input from keyboard
+6.4k Android Studio : Indicate progression with ProgressBar example
+12.2k Golang : On enumeration
+4.7k Apt-get to install and uninstall Golang
+16k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+5.4k Golang : Use modern ciphers only in secure connection
+8.1k Golang : Convert file content to Hex
+8.1k Golang : cannot assign type int to value (type uint8) in range error
+4.2k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+10.4k Elastic Search : Return all records (higher than default 10)
+20.3k Golang : Randomly pick an item from a slice/array example
+17.6k Golang : How to get struct tag and use field name to retrieve data?