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
+20.2k Golang : Count number of digits from given integer value
+36.7k Golang : Display float in 2 decimal points and rounding up or down
+5.4k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+13.2k Golang : Convert(cast) int to int64
+14.3k Golang : Get uploaded file name or access uploaded files
+6.3k Apt-get to install and uninstall Golang
+35.1k Golang : Upload and download file to/from AWS S3
+13.4k Golang : Read from buffered reader until specific number of bytes
+10.1k Golang : Setting variable value with ldflags
+7k Golang : How to setup a disk space used monitoring service with Telegram bot
+5.3k PHP : Hide PHP version information from curl
+7.8k Golang : Scan files for certain pattern and rename part of the files