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
+10.1k Golang : Find age or leap age from date of birth example
+16.5k How to enable MariaDB/MySQL logs ?
+29.7k Golang : Get local IP and MAC address
+4.8k PHP : Get client IP address
+28.3k Golang : Login(Authenticate) with Facebook example
+28.1k Golang : Get time.Duration in year, month, week or day
+6.2k Golang : Use modern ciphers only in secure connection
+3.8k Linux : How to set root password in Linux Mint
+17.4k Golang : Padding data for encryption and un-padding data for decryption
+21.6k Golang : Get ASCII code from a key press(cross-platform) example
+10.1k Golang : How to pipe input data to executing child process?
+27.6k Golang : Saving(serializing) and reading file with GOB