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
有疑问加站长微信联系(非本文作者)

刚看到题目, 我还以为 Go 终于像 Erlang 一样支持 spawn 操作了, 好真的有点小激动呢; 细看了一下代码,不是这个意思。
既然要用 go ,应该发挥 go 的优势:
为什么不 ls 一个 goroutine, grep 一个 goroutine ,两者用 chan string 沟通一下, 这样 可以遍历打印出所有的路径呢?