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
+6.1k Golang : How to write backslash in string?
+6k Golang : How to verify input is rune?
+11.6k Get form post value in Go
+8k Golang : Multiplexer with net/http and map
+11.4k Golang : Concatenate (combine) buffer data example
+31.5k Golang : Get local IP and MAC address
+7.8k Golang : Get today's weekday name and calculate target day distance example
+9.3k Golang : Timeout example
+17.6k Golang : delete and modify XML file content
+27.8k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+9.2k Golang : How to check if a string with spaces in between is numeric?
+9.1k Golang : Write multiple lines or divide string into multiple lines