package mainimport "fmt"import "io/ioutil"import "os/exec"func main() { dateCmd := exec.Command("date") dateOut, err := dateCmd.Output() if err != nil { panic(err) } fmt.Println("> date") fmt.Println(string(dateOut)) grepCmd := exec.Command("grep", "hello") grepIn, _ := grepCmd.StdinPipe() grepOut, _ := grepCmd.StdoutPipe() grepCmd.Start() grepIn.Write([]byte("hello grep\ngoodbye grep")) grepIn.Close() grepBytes, _ := ioutil.ReadAll(grepOut) grepCmd.Wait() fmt.Println("> grep hello") fmt.Println(string(grepBytes)) lsCmd := exec.Command("bash", "-c", "ls -a -l -h") lsOut, err := lsCmd.Output() if err != nil { panic(err) } fmt.Println("> ls -a -l -h") fmt.Println(string(lsOut)) }
执行结果:
> date 2015年 1月23日 星期五 21时29分39秒 CST > grep hello hello grep > ls -a -l -h total 32 drwxr-xr-x 6 itfanr admin 204B 1 23 21:29 . drwxrwxrwx 6 itfanr admin 204B 12 27 09:52 .. -rw-rw-r--@ 1 itfanr admin 721B 1 23 21:29 excute.go drwxr-xr-x 13 itfanr admin 442B 1 22 21:06 github.com
参考:
https://gobyexample.com/spawning-processes
http://tobegit3hub1.gitbooks.io/understanding-linux-processes/content/go_example/spawn.html
3. https://github.com/mmcgrana/gobyexample
有疑问加站长微信联系(非本文作者)