上QQ阅读APP看书,第一时间看更新
How to do it…
The following steps cover the solution:
- Open the console and create the folder chapter01/recipe08.
- Navigate to the directory.
- Create the run.go file with the following content:
package main
import (
"bytes"
"fmt"
"os/exec"
)
func main() {
prc := exec.Command("ls", "-a")
out := bytes.NewBuffer([]byte{})
prc.Stdout = out
err := prc.Run()
if err != nil {
fmt.Println(err)
}
if prc.ProcessState.Success() {
fmt.Println("Process run successfully with output:\n")
fmt.Println(out.String())
}
}
- Run the code by executing go run run.go.
- See the output in the Terminal:
- Create the start.go file with the following content:
package main
import (
"fmt"
"os/exec"
)
func main() {
prc := exec.Command("ls", "-a")
err := prc.Start()
if err != nil {
fmt.Println(err)
}
prc.Wait()
if prc.ProcessState.Success() {
fmt.Println("Process run successfully with output:\n")
fmt.Println(out.String())
}
}
- Run the code by executing go run start.go.
- See the output in Terminal: