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
+21.3k Golang : Convert string slice to struct and access with reflect example
+6.4k Golang : Join lines with certain suffix symbol example
+18.5k Golang : Padding data for encryption and un-padding data for decryption
+9.9k Golang : How to get quoted string into another string?
+14.3k Golang : Execute function at intervals or after some delay
+10.9k Golang : How to pipe input data to executing child process?
+9.4k Golang : Load ASN1 encoded DSA public key PEM file example
+18.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+12k Golang : Encrypt and decrypt data with x509 crypto
+7k Golang : File system scanning
+16.1k Golang : Check if a string contains multiple sub-strings in []string?