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
+18.4k Golang : Write file with io.WriteString
+10.8k Golang : Replace a parameter's value inside a configuration file example
+7.6k Golang : Generate human readable password
+27.5k PHP : Count number of JSON items/objects
+10.5k Golang : Allow Cross-Origin Resource Sharing request
+15.9k Golang : Generate universally unique identifier(UUID) example
+7.4k Gogland : Single File versus Go Application Run Configurations
+7.4k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+6.1k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+6.2k Unix/Linux : Use netstat to find out IP addresses served by your website server
+40.8k Golang : How to check if a string contains another sub-string?
+9.5k Golang : Eroding and dilating image with OpenCV example