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
+14k Golang : Find file size(disk usage) with filepath.Walk
+6.1k Golang : How to check if input string is a word?
+4.5k Golang : How to get capacity of a slice or array?
+3.6k PHP : Fix Call to undefined function curl_init() error
+5.3k Golang : Null and nil value
+10.3k Golang : Convert(cast) uintptr to string example
+11.1k Golang : Date and Time formatting
+9.3k Golang : Perform sanity checks on filename example
+10.5k Golang : Validate email address
+7.2k Golang : Get all countries currencies code in JSON format
+8.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+4.2k Golang : How to write backslash in string?