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
+12.6k Golang : Fix image: unknown format error
+9.7k Golang : Simple image viewer with Go-GTK
+4.8k Linux : Disable and enable IPv4 forwarding
+6.6k Golang : Generate human readable password
+15.4k Golang : File path independent of Operating System
+11.7k Golang : Convert(cast) uintptr to string example
+27.9k Golang : JQuery AJAX post data to server and send data back to client example
+8.8k Golang : Function wrapper that takes arguments and return result example
+50.5k Golang : How to get time in milliseconds?
+12.5k Golang : Check if an integer is negative or positive
+8.9k Golang : Use regular expression to get all upper case or lower case characters example