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
+4.9k Golang : How to pass data between controllers with JSON Web Token
+26.6k Golang : Get executable name behind process ID example
+29.5k Golang : Save map/struct to JSON or XML file
+8.7k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+11.7k Golang : Fuzzy string search or approximate string matching example
+26.9k Golang : Convert file content into array of bytes
+13.8k Golang : Tutorial on loading GOB and PEM files
+19.9k Golang : Append content to a file
+5.9k Linux : Disable and enable IPv4 forwarding
+8k Golang : Ways to recover memory during run time.
+5.3k Golang : The Tao of importing package
+8.8k Golang : How to join strings?