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
+21.1k Generate checksum for a file in Go
+23.5k Golang : Get current file path of a file or executable
+21k Golang : How to read JPG(JPEG), GIF and PNG files ?
+6.1k Golang : Check if one string(rune) is permutation of another string(rune)
+8.8k Golang : Translate language with language package example
+16.2k Golang : [json: cannot unmarshal object into Go value of type]
+4.7k Golang : Error handling methods
+17.6k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+5.2k PHP : Proper way to get UTF-8 character or string length
+11.1k Golang : Listen and Serve on sub domain example
+10k How to test Facebook App on localhost ?
+8.8k Golang : Convert octal value to string to deal with leading zero problem