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
+7.2k Golang : Routes multiplexer routing example with regular expression control
+17.7k Golang : Delete duplicate items from a slice/array
+7.4k Golang : Generate Datamatrix barcode
+21.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+10.5k Golang : Sort and reverse sort a slice of runes
+17.2k Golang : Read binary file into memory
+5k Golang : How to verify input is rune?
+19.5k Golang : Clean up null characters from input data
+11.1k Golang : Forwarding a local port to a remote server example
+7.2k Golang : Number guessing game with user input verification example
+31.3k Golang : Regular Expression for alphanumeric and underscore
+13.9k Golang : How to get Unix file descriptor for console and file