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
+11.9k Golang : Count number of runes in string
+8.6k Golang : Resumable upload to Google Drive(RESTful) example
+12k Golang : How to get a user home directory path?
+17.4k Unmarshal/Load CSV record into struct in Go
+21.4k Golang : simulate tail -f or read last line from log file example
+9.7k Golang : Sieve of Eratosthenes algorithm
+25k Golang : Convert file content into array of bytes
+4.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+3.6k Linux/MacOSX : Search and delete files by extension
+20.1k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+5.1k AWS S3 : Prevent Hotlinking policy