Providing input to a child process
There are two methods you can use to provide input to a child process: set cmd.Stdin
to a stream or use cmd.StdinPipe
to obtain a writer to send the input to the child process.
How to do it...
- Create the command:
// Run grep and search for a word cmd := exec.Command("grep", word)
- Provide the input to the process by setting the
Stdin
stream:// Open a file input, err := os.Open("input.txt") if err != nil { panic(err) } cmd.Stdin = input
- Run the program and wait for it to end:
if err = cmd.Start(); err != nil { panic(err) } if err = cmd.Wait(); err != nil { panic(err) }
Alternatively, you can provide a streaming input using a pipe.
- Create the command:
// Run grep and search for a word cmd := exec.Command("grep", word)
- Get the input pipe:
input, err:=cmd.StdinPipe() if err!=nil { panic(err) }
- Send the input to the program through the pipe. When done, close...