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
+8.5k Golang : Count leading or ending zeros(any item of interest) example
+10.4k Golang : How to profile or log time spend on execution?
+4.9k Fix Google Analytics Redundant Hostnames problem
+7.6k Golang : Handling Yes No Quit query input
+12.3k Golang : Pagination with go-paginator configuration example
+63k Golang : Convert HTTP Response body to string
+9.2k Golang : Inject/embed Javascript before sending out to browser example
+5.5k Javascript : Shuffle or randomize array example
+7.7k Golang : How to stop user from directly running an executable file?
+17.5k Golang : Find file size(disk usage) with filepath.Walk
+6.4k Golang & Javascript : How to save cropped image to file on server
+12.5k Golang : List running EC2 instances and descriptions