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
+16.7k Golang : Capture stdout of a child process and act according to the result
+6.8k Web : How to see your website from different countries?
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+4.6k Fix Google Analytics Redundant Hostnames problem
+41.1k Golang : How do I convert int to uint8?
+5.1k Golang : Return multiple values from function
+21.5k Golang : How to reverse slice or array elements order
+15k nginx: [emerg] unknown directive "ssl"
+7.7k Golang : Gomobile init produce "iphoneos" cannot be located error
+6.2k PHP : Proper way to get UTF-8 character or string length
+5.1k Golang : Generate Interleaved 2 inch by 5 inch barcode
+5.6k Cash Flow : 50 days to pay your credit card debt